嗨,我在 java 中遇到这个问题,尝试使用 swing 创建 UI。我遇到了一个无法解决的问题,需要一些帮助。
我想要发生的是,当单击按钮时,它将它传递给在方法 run() 中创建的对象 ui。
public class MainTest{
public static void main(String[] args){
MainTest test = new MainTest();
test.run();
}
public void run(){
UITest ui = UITest();
ui.start();
while (true){
if (ui.getClicked()) break;
}
System.out.println("Working this far");
}
public class UITest{
private JFrame frame;
private boolean clicked = false;
public void start(){
EventQueue.invokeLater(new JframeCreator());
}
private class JframeCreator implements Runnable{
public void run(){
createUI();
frame.setVisible(true);
}
}
private void createUI(){
frame = new JFrame();
frame.setResizable(false);
frame.setSize(353, 264);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("test");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clicked = true;
}
});
btnNewButton.setBounds(118, 150, 89, 32);
frame.getContentPane().add(btnNewButton);
}
public boolean getClicked(){
return clicked;
}
}
对我来说,这看起来应该可以工作,但它没有到达输出“到目前为止工作”的代码。我点击按钮但没有任何反应
一旦我添加输出值,它确实可以工作。现在,当我单击按钮时,它就会运行。
public void run(){
//previous code
while(true){
if (ui.getClicked()) break;
System.out.println("Not working"); //Added
}
System.out.println("working this far");
}
我似乎无法弄清楚为什么它会这样工作以及我缺少什么。
希望我说得足够清楚。
最佳答案
单击按钮发生在与运行循环的线程不同的线程中。私有(private)变量的变化对于循环线程是不可见的,因此它继续循环。
您应该将clicked
变量设为 volatile
。这将确保对其感兴趣的其他线程可以看到其中的更改。
打印命令可能会导致内存模型允许新值对该线程可见,但当然,这不是正确的方法。
当然,在 boolean 变量上等待紧密循环也不是那么可取。
关于Java Swing Jbutton 访问另一个类中按下的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29064760/