2017-03-03 62 views
0

我有一个Java线程的问题。 假设我们有一个名为Main的主线程和一个名为Frame的第二线程。此外,Frame还有一个JButton。在Main中,我们有一个只要在JFrame中按下按钮就会运行的循环。用第二个线程停止主线程

我写了一个简短的例子为此,第一帧类别:

public class Frame extends javax.swing.JFrame{ 

    private boolean isRunning; 

    public Frame() { 
     initComponents(); 
     isRunning = true; 
    } 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
     isRunning = false; 
    }           

    public boolean isRunning(){ 
     return isRunning; 
    } 

    // ***** Some netbeans stadard stuff ***** 
    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code">       
    private void initComponents() { 

     jButton1 = new javax.swing.JButton(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jButton1.setText("Stop"); 
     jButton1.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton1ActionPerformed(evt); 
      } 
     }); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addGap(167, 167, 167) 
       .addComponent(jButton1) 
       .addContainerGap(178, Short.MAX_VALUE)) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
       .addContainerGap(153, Short.MAX_VALUE) 
       .addComponent(jButton1) 
       .addGap(124, 124, 124)) 
     ); 

     pack(); 
    }// </editor-fold>       



    public void main() { 
     /* Set the Nimbus look and feel */ 
     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new Frame().setVisible(true); 
      } 
     }); 
    } 

    // Variables declaration - do not modify      
    private javax.swing.JButton jButton1; 
    // End of variables declaration     

    // ***** End of this netbeans stuff ***** 
} 

现在主类

public class Main { 
    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     Frame f = new Frame(); 
     f.main(); 

     for (int i = 0; f.isRunning(); i++) { 
      System.out.println((i + 1)); 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException ex) { 
       Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 
} 

但是,如果我按下按钮,没有任何反应。我也试图与“实现Runnable”扩展该类框架和覆盖了的run() - 方法,并开始在此主:

Thread t = new Thread(new Frame()); 
    t.start(); 

,但我得到了同样的问题。

请问,有人可以帮助我吗?

问候马蒂亚斯

+1

*“Nothing happens”*不是有用的描述 - 你应该使用你的调试器来找出问题所在。然而,你的设计/方法看起来倒退 - UI应该是主线程,而长期持久的任务应该放在单独的线程中。 – UnholySheep

+0

你应该退一步并创建一个真实的[mcve]。我们不能运行你的代码,只是看看它;从我所能看到的......没有什么能够解释为什么当你点击那个按钮时,你的Main main()中的循环不应该停止;至少在一段时间之后;但正如Unholy所说:你的描述太模糊了。 – GhostCat

回答

0

你没有显示正确的Frame

Main您要创建一个新的Frame实例...

public class Main { 
    public static void main(String[] args) { 
     Frame f = new Frame(); 
     f.main(); 

     for (int i = 0; f.isRunning(); i++) { 
      // ... 
     } 
    } 
} 

,然后在Frame你创建另一个一个...

public class Frame extends javax.swing.JFrame{ 
    // ... 

    public void main() { 
     // ...   
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new Frame().setVisible(true); 
      } 
     }); 
    } 

    // ... 
} 

Frame你”已在您的Main课程中创建的课程不是正在显示的课程,这就是为什么f.isRunning()始终返回true。你可以通过显示正确的帧来解决这个问题:

public class Frame extends javax.swing.JFrame{ 
    // ... 

    public void main() { 
     // ...   
     Frame ref = this; 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       ref.setVisible(true); 
      } 
     }); 
    } 

    // ... 
} 
+0

你好Janez, 非常感谢你。我在这一刻找到了另一种解决方案。因为,我只使用这些对象中的一个,所以我们可以使运行静态。但在我看来,这是不好的解决方案。你的解决方案要好得多。 :) 再次感谢。 – Brayn