/*纯粹是闲着没事做才这样写*/
/*实现两个数相加*/
/*错误代码*/
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ComputerAdd extends JFrame{
/**
*
*/
private static final long serialVersionUID = -2168495073747021871L;
JLabel l1, l2;
JTextField tf1;
JTextField tf2;
JButton bt;
public ComputerAdd(){
l1 = new JLabel("Please input two number:");
l2 = new JLabel();
tf1 = new JTextField();
tf2 = new JTextField();
bt = new JButton(" = ");
ButtonListener b = new ButtonListener();
bt.addActionListener(b);
setLayout(new GridLayout(0,1));
add(l1);
add(tf1);
add(tf2);
add(bt);
add(l2);
setTitle("ComputerAdd");
setSize(300, 300);
setVisible(true);
}
@SuppressWarnings("unused")
public static void main(String args[]){
ComputerAdd c = new ComputerAdd();
}
}
class ButtonListener implements ActionListener{
ComputerAdd a = new ComputerAdd(); //<-------错在这里了 不能再实例化一次 传参实现
public void actionPerformed(ActionEvent e){
int n1, n2, sum;
n1 = Integer.parseInt(a.tf1.getText());
n2 = Integer.parseInt(a.tf2.getText());
sum = n1 + n2;
a.l2.setText("" + sum);
}
}
改正后正确代码:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ComputerAdd extends JFrame{
JFrame f;
JLabel l1, l2;
JTextField tf1;
JTextField tf2;
JButton bt;
public ComputerAdd(){
f = new JFrame();
l1 = new JLabel("Please input two number:");
l2 = new JLabel();
tf1 = new JTextField();
tf2 = new JTextField();
bt = new JButton(" = ");
ButtonListener b = new ButtonListener(tf1, tf2, l2);
bt.addActionListener(b);
setLayout(new GridLayout(0,1));
add(l1);
add(tf1);
add(tf2);
add(bt);
add(l2);
setTitle("ComputerAdd");
setSize(300, 300);
setVisible(true);
}
public static void main(String args[]){
ComputerAdd c = new ComputerAdd();
}
}
class ButtonListener implements ActionListener{
JLabel l2;
JTextField tf1,tf2;
public ButtonListener(JTextField tf1, JTextField tf2, JLabel l2){
this.l2 = l2;
this.tf1 = tf1;
this.tf2 = tf2;
}
public void actionPerformed(ActionEvent e){
int n1, n2, sum;
n1 = Integer.parseInt(tf1.getText());
n2 = Integer.parseInt(tf2.getText());
sum = n1 + n2;
l2.setText("" + sum);
}
}