gpt4 book ai didi

java - Java 中使用 JFrame 的监听器

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:31 24 4
gpt4 key购买 nike

我现在正在学习 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 会产生一些垃圾值,从而产生错误。我应该怎么做才能让它正确处理它而不 hibernate 线程?

最佳答案

解决这个问题的一些方法。使用 JDialog - 默认提供模式阻塞,监听器机制 - 稍后回调值,或者使你的代码阻塞

JDialog

public class test extends JDialog {
...
private int N;

public int setVisible() {
this.setVisible(true);
return N;
}

public test() {
super(null, ModalityType.APPLICATION_MODAL);
// <== pass parent window here if you have one, you don't seem to..
...
}

阻止示例

  • 使用java.util.concurrent.CountDownLatch

代码

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

}
});
}

关于java - Java 中使用 JFrame 的监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com