2017-03-03 2 views
0

Javaスレッドに問題があります。 メインと呼ばれるメインスレッドと、フレームと呼ばれる第2のスレッドがあるとします。また、フレームにはJButtonがあります。 Mainでは、JFrameにButtonをプッシュしている間はループを実行しています。メインスレッドを2番目のスレッドで停止する

私は最初のフレーム・クラス、このために短い例を書いた:メインクラスに今

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); 
      } 
     } 
    } 
} 

をしかし、私はボタンを押した場合、何も起こりません。

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

が、私は同じ問題を取得します。方法として、メインでこれを起動する - 私はまた)(「Runnableを実装します」と実行を上書きして、クラスの枠を拡張しようとしました。

どうかお手伝いできますか?

敬具マティアス

+1

※「何も起こりません」*は参考になりません。*問題の原因を特定するには、デバッガを使用する必要があります。しかし、あなたの設計/アプローチは逆のように見える - UIはメインスレッドでなければならず、長く持続するタスクは別々のスレッドに入れなければならない。 – UnholySheep

+0

元に戻って真の[mcve]を作成する必要があります。コードを実行することはできません。ちょうどそれを見てください。私が見ることのできるところから、メインの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にあなたはまだ別のものを作成している... Frame

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

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

    // ... 
} 

いるあなた」 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

こんにちはジャニス、 ありがとうございます。私はこの瞬間に別の解決策を見つけました。これらのオブジェクトのうちの1つだけを使用するので、静的に実行することができます。しかし、私の意見では、それは悪い解決策です。あなたのソリューションははるかに優れています。 :) もう一度ありがとう。 – Brayn

関連する問題