简体   繁体   中英

Stop the main-Thread with a second Thread

I have a problem with Java Threads. Suppose we have a main-Thread called Main and a second Thread called Frame. Besides, Frame has a JButton. In Main, we have a loop which is running as long as pushed the Button in JFrame.

I wrote a short example for this, first the Frame-Class:

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 *****
}

Now the Main-Class

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

But, if I push the Button, nothing happens. I also tried to extend the Class Frame with "implements Runnable" and overwrote the run()-Method and start this in Main with:

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

but I get the same problem.

Please, can anybody help me?

Best regards Matthias

You're not showing the right Frame !

In Main you're creating a new Frame instance...

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

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

and then in Frame you're creating yet another one ...

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

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

    // ...
}

The Frame that you've created in your Main class is not the one that's showing up and that's why f.isRunning() always returns true . You can fix this by showing the correct frame:

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

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM