在Java中使用JFrame的侦听器

在Java中使用JFrame的侦听器,java,swing,actionlistener,Java,Swing,Actionlistener,我现在正在学习ActionListeners的基础知识,我一直在这里寻求帮助,但无法完全找到/理解我做错了什么 我有一个实现主调用的类(客户机): ... public static void main(String[] args) { Myframe test = new Myframe(); N = test.setVisible(); // N is an integer ... } 然后,我的框架中的代码: public class test extends JF

我现在正在学习ActionListeners的基础知识,我一直在这里寻求帮助,但无法完全找到/理解我做错了什么

我有一个实现主调用的类(客户机):

...
public static void main(String[] args) {

    Myframe test = new Myframe();

    N = test.setVisible(); // N is an integer

...
}
然后,我的框架中的代码:

public class test extends JFrame {

    private JPanel contentPane;
    private int N;

    public int setVisible(){

        this.setVisible(true);
        return N;

    }

    /**
     * Create the frame.
     */
    public test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JButton btnOk = new JButton("OK");
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                N=5;
                dispose();

            }
        });
        contentPane.add(btnOk, BorderLayout.SOUTH);
    }

}
问题是:程序在继续运行之前没有等待按钮被按下,N会导致一些垃圾值,从而产生错误。
我应该怎么做才能让它在不休眠线程的情况下正确处理它?

一些方法可以解决这个问题。使用JDialog-默认情况下提供模式阻塞,侦听器机制-稍后使用值回调,或使代码阻塞

模式窗体
公共类测试扩展JDialog{
...    
私人int N;
公共int setVisible(){
此.setVisible(true);
返回N;
}
公开考试(){
super(null,ModalityType.APPLICATION\u MODAL);

//使用模态的
JDialog
而不是
JFrame
,JFrame设计用于在其可见点阻塞,直到关闭为止

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }


    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JDialog frame = new JDialog();
                TestPane testPane = new TestPane();
                frame.setTitle("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(testPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                System.out.println("The value was - " + testPane.getValue());
            }
        });
    }

    public class TestPane extends JPanel {

        private int n;

        public TestPane() {
            JButton btnOk = new JButton("OK");
            btnOk.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {

                    n = 5;
                    SwingUtilities.windowForComponent(TestPane.this).dispose();

                }
            });
        }

    }

    public int getValue() {
        return n;
    }

}

仔细看一看,了解更多细节,为什么?一个
JDialog
可以用更少的代码完成同样的工作,这就是它的设计目的……是的,我同意,我太专注于获得第一个答案,以获得正确的答案。
public class test extends JFrame {
    ....    
    private CountDownLatch latch;
    private int N;

    public int setVisible() throws InterruptedException{

        latch = new CountDownLatch(1);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                setVisible(true);
            }
        });

        latch.await();   // <== block until countDown called
        return N;
    }

    public test() {           
        ...
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                N=5;
                latch.countDown();   <== will unblock await() call
                dispose();

            }
        });
        ...
    }

}
public class test extends JFrame {
    ... 
    private Listener listener;

    public static interface Listener {
        void setN(int n);
    }

    public void setVisible(Listener listener) throws InterruptedException {
        this.listener = listener;   // <== save reference to listener
        setVisible(true);
    }

    public test() {
        ...
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                listener.setN(5);  // <== call listener
                dispose();

            }
        });
    }
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }


    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JDialog frame = new JDialog();
                TestPane testPane = new TestPane();
                frame.setTitle("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(testPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                System.out.println("The value was - " + testPane.getValue());
            }
        });
    }

    public class TestPane extends JPanel {

        private int n;

        public TestPane() {
            JButton btnOk = new JButton("OK");
            btnOk.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {

                    n = 5;
                    SwingUtilities.windowForComponent(TestPane.this).dispose();

                }
            });
        }

    }

    public int getValue() {
        return n;
    }

}