JAVA 按钮 监听

来源:百度知道 编辑:UC知道 时间:2024/05/25 00:42:26
请问下面的一段代码,如果才能实现监听,使按键按一下,上面文本有显示相应的数字.
import java.awt.*;
import javax.swing.*;
public class JiSuan extends JFrame
{
public JiSuan()
{
Container container=getContentPane();
container.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,3));
for(int i=1;i<=9;i++)
{
p1.add(new JButton(""+i));
}
p1.add(new JButton(""+0));
p1.add(new JButton("+/-"));
p1.add(new JButton("."));
JPanel p2=new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(4,2));
p2.add(new JButton("/"));
p2.add(new JButton("sqrt"));
p2.add(new JButton("*"));
p2.add(new JButton("%"));
p2.add(new JButton("-"));
p2.add(new JButton("1/x"));
p2.add(new JButton("+"));
p2.add(new JButton("=")

class MyAction extends immplements ActionLister {
public void actionPerformed(ActionEvent e) {
String str = (JButton)e.getSource).getText();
if (str == "你的按钮上面的字") {
new JTextArea().setText(str);
}
}
}
这样就可以了。然后上面每个按钮都监听上,
比如
new JButton(""+i).addActionListener(new MyAction());
每个都添加就好了。。