java中如何同时监听多个事件,下面是我写的code,我想实现分别点击a,b,c按钮分别出现不同的行为,谢谢

importjava.awt.*;importjava.awt.event.*;importjava.awt.BorderLayout;importjava.awt.Co... import java.awt.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;

public class Listener implements ActionListener {
private JFrame frame;
private JTextField tf;
private JButton[] allButtons;
private JButton a;
private JButton b;
private JButton c;

public static void main(String[] args) {
Listener two = new Listener();
two.init();
}

public void init() {
frame = new JFrame("Calculator");
Container contentPane = frame.getContentPane();
contentPane.add(new Label("计算器"), BorderLayout.NORTH);
frame.setLayout(new BorderLayout());
//Container contentPane = frame.getContentPane();
JPanel centerPanel =new JPanel();
JPanel northPanel =new JPanel();
JPanel southPanel =new JPanel();

southPanel.setLayout(new GridLayout(4,4));
tf = new JTextField(30);
centerPanel.add(tf);

for (int i = 0; i < allButtons.length; i++) {
allButtons[i].addActionListener(this);}

a = new JButton("words");
b = new JButton("show");
c = new JButton("change");

allButtons = new JButton[16];
String str = "123+456-789*0.=/";
for (int i = 0; i < 16; i++) {
allButtons[i] = new JButton(str.substring(i, i + 1));
}
southPanel.setLayout(new GridLayout(4, 4));
northPanel.setLayout(new GridLayout(1, 3));
frame.add(southPanel, BorderLayout.SOUTH);
for (int i = 0; i < allButtons.length; i++) {
southPanel.add(allButtons[i]);
}
northPanel.add(a);
northPanel.add(b);
northPanel.add(c);
frame.add(southPanel,BorderLayout.CENTER);
frame.add(northPanel,BorderLayout.SOUTH);
contentPane.add(tf, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setVisible(true);

// 注册监听程序
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {
String s = "This is my first java program and thank you for your support";
tf.setText(s);
c.setBackground(Color.CYAN);
}
}
展开
 我来答
papercut999
2009-10-12 · TA获得超过1786个赞
知道小有建树答主
回答量:1644
采纳率:0%
帮助的人:1104万
展开全部
在public void actionPerformed(ActionEvent e) 方法中加入如下代码:
if (e.getSource()==a) {
System.out.println("a");
} else if (e.getSource() == b) {
System.out.println("b");
} else if (e.getSource() == c) {
System.out.println("c") ;
}

另外:你似乎还有语法错误:
for (int i = 0; i < allButtons.length; i++) {
allButtons[i].addActionListener(this);}
这句话的位置没有放对,放这里肯定会报空指针,说你的allButton为空
最好放在你的注释:注册监听程序
这个之后
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式