import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyActionListener implements ActionListener {
JFrame jf;
JPanel jp;
JButton button1, button2;
TextArea tf1, tf2;
public MyActionListener() {
jf = new JFrame("twoaction");
button1 = new JButton("小明");
button2 = new JButton("光明");
tf1 = new TextArea();
tf2 = new TextArea();
jp = new JPanel();
button2.addActionListener(this);
button1.addActionListener(new secondbutton());
jp.add(button1);
jp.add(button2);
Label label1 = new Label("小明");
Label label2 = new Label("光明");
jf.setLayout(new GridLayout(5, 1));
jf.add(label1);
jf.add(tf1);
jf.add(label2);
jf.add(tf2);
jf.add(jp);
jf.setSize(500, 500);
jf.setVisible(true);
}
public static void main(String[] args) {
//MyActionListener action = new MyActionListener();
new MyActionListener();
}
@Override
public void actionPerformed(ActionEvent e) {
tf1.append(e.getActionCommand()+"说:" +tf2.getText()+ "\n");
tf2.setText(null);
}
// 通过内部类来增加button的监听器
class secondbutton implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
tf2.append(e.getActionCommand()+"说:" + tf1.getText()+ "\n");
tf1.setText(null);
}
}
}
还可以的实例
MyActionListener监听按钮
最新推荐文章于 2022-10-04 22:15:19 发布