【发布时间】:2014-07-14 10:35:52
【问题描述】:
我有一个 Java 程序,我计划从 GUI 中获取输入,然后使用该输入在 main() 中进行处理。我正在使用Eclipse。
我正在向 GUI JFrame 发送一个HW 对象(称为HWObj),并检查对象中的boolean 字段以继续在main() 中处理。
InputWindow 是扩展JPanel 实现ActionListener 的自定义对象
它包含对当前JFrame(parentFrame) 的引用。在 InputWindow 中单击JButton 时,我编写了一个自定义ActionListener,它将HWObj.check 的值设置为true 并处理parentFrame。这应该会导致在main() 中恢复执行。HW 类的代码如下:
import java.awt.*;
import javax.swing.*;
public class HW {
//globals
boolean check;
public HW() {
//initialisations
check = false;
}
public static void main(String args[]) {
final HW problem = new HW();
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Create and set up the window.
JFrame frame = new JFrame("Select folders");
frame.setPreferredSize(new Dimension(640, 480));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
InputWindow Directories = new InputWindow(problem, frame);
Directories.setOpaque(true);
frame.add(Directories);
//Display the window.
frame.pack();
frame.setVisible(true);
}
});
} catch(Exception e) {
System.out.println("Exception:"+e.getLocalizedMessage());
}
while(!problem.finish);
//Do processing on problem
System.out.println("Done");
}
}
gui中的Actionlistener如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InputWindow extends JPanel
implements ActionListener {
private static final long serialVersionUID = 4228345704162790878L;
HW problem;
JFrame parentFrame;
//more globals
public InputWindow(HW problem, JFrame parentFrame) {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
this.parentFrame = parentFrame;
this.problem = problem;
JButton finishButton = new JButton("Finish");
finishButton.setActionCommand("fin");
finishButton.addActionListener(this);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(finishButton, gbc);
//Initialize buttons and text areas and labels
//Code removed for ease of reading
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("fin")) {
//Do a lot of stuff, then
this.removeAll();
parentFrame.dispose();
problem.check = true;
}
}
}
我已经检查过了,这个功能的控制通常是在按钮点击时出现的。
现在,我希望它返回到main,并退出while 循环,然后继续处理。
这不会发生。 eclipse中的调试器只显示主线程正在运行,当我尝试暂停它时,我看到线程卡在while循环中。但是,如果我尝试单步执行,它会按预期退出 while 循环,然后继续。但是,在我手动尝试调试它之前,它一直停留在 while 循环中。
问题是什么?为什么它没有按预期恢复main thread?
我该如何解决这个问题?
【问题讨论】:
-
需要完整的代码。
-
完整的代码庞大而臃肿。你能告诉我你想要哪些零件吗?
-
创建一个新框架然后销毁它的类的代码,以及你在while循环中卡住的那个。
-
“相关”部分会很好。如果您将代码提取到方法中,而不是用代码填充主方法,那么阅读起来会容易得多。 main 方法应该什么都不做,只是启动你的应用程序。
-
您想要哪些零件? == 发布一个 SSCCE/MCVE,简短、可运行、可编译、生成上午问题
标签: java eclipse swing user-interface user-input