package com.zhengrong.www;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Calculator extends JFrame implements ActionListener{
Calculator(){
setTitle("计算器");
setSize(500,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JButton btn = new JButton("=");
JLabel jlb = new JLabel("+");
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JTextField t3 = new JTextField(10);
t1.setEditable(true);
t2.setEditable(true);
Panel p = new Panel();
add(p);
p.add(t1);
p.add(jlb);
p.add(t2);
p.add(btn);
p.add(t3);
p.setBackground(Color.yellow);
validate();
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
int result = Integer.parseInt(t1.getTitle())+Integer.parseInt(t2.getText());
t3.setText(String.valueOf(result));
}
}
public class Test {
public static void main(String[] args) {
new Calculator();
}
}
------解决方案--------------------
1. t1,t2,t3定义到构造方法里了,actionPerformed当然拿不到;
2. t1.getTitle(),你确定没有写错;应该是t1.getText();
3. 帮你改了下,自己看看吧!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Calculator extends JFrame implements ActionListener
{
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JTextField t3 = new JTextField(10);
Calculator()
{
setTitle("计算器");
setSize(500, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JButton btn = new JButton("=");
JLabel jlb = new JLabel("+");
t1.setEditable(true);
t2.setEditable(true);
Panel p = new Panel();
add(p);
p.add(t1);
p.add(jlb);
p.add(t2);
p.add(btn);
p.add(t3);
p.setBackground(Color.yellow);
validate();
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int result = Integer.parseInt(t1.getText()) //你确定这里你的对了?
+ Integer.parseInt(t2.getText());
t3.setText(String.valueOf(result));
}
}
public class Test
{
public static void main(String[] args)
{
new Calculator();
}
}