在我的程序中,我需要等待用户从jframe输入。使用第一个输入完成用户后,他们按JButton。这称我为我所做的班级的构造函数:人类创造者。在构造函数中,我需要用户具有更多的输入。我发挥了两个功能来等待并通知。但是,当代码等待时,所有内容都会冻结,并且Jframe不会更新到应该的内容。
这是第一个按钮preforms
的动作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(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
}
但是,当按下启动布顿时,屏幕会冻结并且不会更新,以便可以按下cont。
首先查看摆动中的并发。Swing使用单个线程从EDT内部执行任何长期运行或阻止操作(例如调用wait
(,然后将其冻结您的程序,用户必须终止它。
您有两个基本选择。您可以使用模态对话框从用户收集信息,请参阅如何制作对话框,该对话框将在显示其显示的点上阻止代码的执行,而无需阻止整个EDT或使用观察者模式,该模式可以生成通知用户提供了您期望的任何信息。
说实话,模态对话框通常更容易,并且可以帮助防止意外的副作用
这个...
make();//This is a function contained in HumanTrainer that only calls wait(); With the proper try and catch
似乎是您问题的核心,但是如果没有更多的信息和上下文,就不可能真正建议您要做什么,但是我建议您看看模型视图 - 控制器并将您的代码分为更合适的层
首先,您可能需要用{}
关闭循环,以免两次循环整个代码。另外,您应该检查wait()
和notify()
是否在没有Java AWT的情况下单独测试它们是否正常工作。