【发布时间】:2015-03-16 04:27:47
【问题描述】:
您好,我在 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");
}
我似乎无法弄清楚为什么它会以这种方式工作以及我缺少什么。
希望我说得足够清楚。
【问题讨论】: