我是摇摆新手,仍在学习它的来龙去脉。我编写了一个基本代码并开始尝试使用 EDT。这是代码:
public class SwingDemo2 extends Thread implements ActionListener {
JLabel jl;
SwingDemo2() {
JFrame jfr = new JFrame("Swing Event Handling");
jfr.setSize(250, 100);
jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jl = new JLabel("Press a button!", SwingConstants.CENTER);
System.out.println("After Label: " + SwingUtilities.isEventDispatchThread());
JButton jb1 = new JButton("OK");
jb1.setActionCommand("OK");
jb1.addActionListener(this);
JButton jb2 = new JButton("Reset");
jb2.setActionCommand("Reset");
jb2.addActionListener(this);
jfr.add(jl, BorderLayout.NORTH);
jfr.add(jb1, BorderLayout.WEST);
jfr.add(jb2, BorderLayout.EAST);
System.out.println("After adding: " + SwingUtilities.isEventDispatchThread());
jfr.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("In main: " + SwingUtilities.isEventDispatchThread());
new SwingDemo2();
}
});
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand() == "OK") {
System.out.println("In OK: " + SwingUtilities.isEventDispatchThread());
jl.setText("You pressed Ok");
}
else if (ae.getActionCommand() == "Reset") {
System.out.println("In Reset: " + SwingUtilities.isEventDispatchThread());
jl.setText("You pressed Reset");
}
}
}
我添加了一些isEventDispatchThread()
方法来验证我所在的线程。除了 GUI 之外,控制台中的消息还有:
In main: true
After Label: true
After adding: true
In OK: true
In Reset: true
似乎我一直在 EDT。我的问题是,在jfr.setVisible(true)
语句之后SwingDemo2()
构造函数不应该返回main()
并且不应该是 EDT 的结尾吗?
在我第一次按下 GUI 中的任何按钮之前,我等了很多秒,那么为什么我的事件处理仍在 EDT 中完成?这不应该给 EDT 足够的时间来终止吗?
提前谢谢!