想不明白,关于事件处理!
这几天在学事件处理,学到事件队列时写了下面一个程序。
程序大概就是:
有两个按钮和一个文体框
点击button1,文体框就显示信息。
点击button2,触发button1的“点击”事件。
但问题就在这里:点击button2后没有反应!
麻烦大家帮我找找原因!
//=====================================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventTestFrame extends JFrame implements ActionListener
{
public static int counter;
JButton button1;
JButton button2;
JTextField textField;
EventQueue queue;
public EventTestFrame()
{
setBounds(300,300,300,150);
counter = 0;
button1 = new JButton("button1");
button2 = new JButton("button2");
textField = new JTextField();
getContentPane().add(button1,BorderLayout.NORTH);
getContentPane().add(button2,BorderLayout.SOUTH);
getContentPane().add(textField,BorderLayout.CENTER);
queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
//取得事件队列
button1.addActionListener(this);
button2.addActionListener(new MyListener());
}
public void actionPerformed(ActionEvent e)
{
counter++;
textField.setText(String.valueOf(counter)
+ " ,source:" + e.getActionCommand());
}
private class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
queue.postEvent(new ActionEvent(button1,
ActionEvent.ACTION_PERFORMED,"button2"));
/*想通过点击button2来触发button1的点击事件*/
}
}
}
public class MyPostEventTest
{
public static void main(String[] args)
{
EventTestFrame frame = new EventTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}