【发布时间】:2017-04-25 22:55:31
【问题描述】:
在我的程序中,我需要等待用户从 JFrame 输入。当用户完成第一个输入时,他们按下 JButton。这为我创建的一个类调用了一个构造函数:HumanTrainer。在构造函数中,我需要用户有更多的输入。我做了两个函数来等待和通知。但是当代码等待时,一切都冻结了,JFrame 没有更新到它应该更新的状态。
这是第一个按钮执行的操作
startingButton.addActionListener((e)->{
Trainer[]t=new Trainer[2];//HumanTrainer extends Trainer
String[]names=new String[2];
for(int a=0;a<2;a++)
names[a]=((JTextField)(startingInputs[2][1+a])).getText();
grid.removeAll();//The JPanel that the Frame has
Frame.repaint();//The JFrame
Frame.validate();
if(isHuman[0])
t[0]=new HumanTrainer(names[0],grid,Frame);//The constructor
if(isHuman[1])
t[1]=new HumanTrainer(names[1],grid,Frame);
});
以及 HumanTrainer 的构造函数
HumanTrainer(String name,JPanel grid,JFrame Frame){
super(name);
GridBagConstraints manager=new GridBagConstraints();
manager.gridx=0;
manager.gridy=0;
manager.gridheight=1;
manager.gridwidth=1;
manager.fill=GridBagConstraints.HORIZONTAL;
Font Format=new Font("Courier New",Font.PLAIN,14);
JButton cont=new JButton("Continue");//This is the button that when clicked should run the function that notifies
grid.add(cont,manager);
grid.repaint();//One of these four things SHOULD change the view of the frame
grid.validate();
Frame.repaint();
Frame.validate();
System.out.print("TEST");//This prints
cont.addActionListener((e)->{
made();//This is a function contained in HumanTrainer that only calls notify();
});
make();//This is a function contained in HumanTrainer that only calls wait(); With the proper try and catch
}
但是当 starterButton 被按下时,屏幕会冻结并且不会更新,因此可以按下 cont。
【问题讨论】:
-
如果您想等待用户输入,请使用模态
JDialog而不是JFrame -
@MadProgrammer 但是在代码继续创建两个培训师之前,我需要来自 HumanTrainer 构造函数的输入。使用 JDialog 不会暂停代码执行。
-
“使用 JDialog 不会暂停代码执行” - 嗯,是的,他们会这样做,除非您在 EDT 之外执行代码(或不使用模态对话框),这意味着您还有其他问题需要处理
-
根据您对上下文外代码的描述,在 EDT 上下文中调用
wait将阻止 EDT 并冻结您的程序 -
你能告诉我怎么做吗,也许我对 JDialogs 的了解并不完整。如果您愿意,我认为它们只会限制与原始框架的交互。我不认为你也可以暂停代码。 @MadProgrammer
标签: java swing jframe wait notify