【发布时间】:2014-02-01 22:53:57
【问题描述】:
这是一个启动新窗口(子表单)的应用程序。在提交此子表单时,应该会处理返回的数据并更新父表单。但是,启动子表单时程序没有响应。有人可以解释为什么会发生这种情况以及我应该如何解决它?
public class FormCondition
{
private JLabel nameLabel;
private JTextField name;
private JButton create;
private Lock lock;
private Condition cond;
private String str;
public FormCondition()
{
lock = new ReentrantLock();
cond = lock.newCondition();
create = new JButton("Create");
nameLabel = new JLabel("Name");
name = new JTextField();
name.setEditable(false);
create.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == create)
{
try
{
lock.lock();
try
{
Runnable r = new Runnable()
{
@Override
public void run()
{
System.out.println("Starting a new Thread");
new newForm();
}
};
new Thread(r).start();
System.out.println("about to wait");
cond.await();
name.setText(str);
}
finally
{
lock.unlock();
}
}
catch (InterruptedException e1)
{
// empty
}
}
}
});
JFrame frame = new JFrame("Main form");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
panel.add(nameLabel);
panel.add(name);
panel.add(create);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setSize(200, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setName(String name)
{
str = name;
System.out.println("Name received is: " + str);
}
class newForm implements ActionListener
{
private JLabel nameLabel;
private JTextField name;
private JButton go;
public newForm()
{
nameLabel = new JLabel("Name");
name = new JTextField();
go = new JButton("Go");
JFrame frame=new JFrame("Second form");
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(0,2));
panel.add(nameLabel);
panel.add(name);
panel.add(go);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setSize(200,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == go)
{
lock.lock();
try
{
String string = name.getText();
System.out.println("Name entered is: " + str);
setName(str);
cond.signal();
System.out.println("Signalled");
}
finally
{
lock.unlock();
}
}
}
}
public static void main(String[] str)
{
new FormCondition();
}
}
【问题讨论】:
-
看起来有人需要阅读Swing threading model。您只能从 EDT 创建和操作 Swing 类。该代码违反了这一点。
-
请参阅The Use of Multiple JFrames, Good/Bad Practice? IT 似乎您正在尝试获得
JDialog的行为,尽管我建议将其设为模态以实际阻止用户访问主窗体,直到对话框被关闭。
标签: java swing concurrency