小小计算器的设计
我的计算器为什么相加后的结果不对呀,请高手指点一下.代码如下:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JWindow1 extends JFrame{
JButton but1=new JButton( "+ ");JButton but2=new JButton( "- ");
JButton but3=new JButton( "× ");JButton but4=new JButton( "÷ ");
JTextField text1=new JTextField(6);
JTextField text2=new JTextField(6);
JTextField text3=new JTextField(6);
public JWindow1(){
super( " 小小计算器 ");
Container c=getContentPane();
c.setLayout(new FlowLayout());
JPanel panel1=new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "操作数、结果 "));
panel1.setLayout(new GridLayout(3,2));
panel1.add(new JLabel( "操作数: "));
panel1.add(text1);
panel1.add(new JLabel( "操作数 "));
panel1.add(text2);
panel1.add(new JLabel( "结 果: "));
panel1.add(text3);
c.add(panel1,BorderLayout.WEST);
JPanel panel2=new JPanel();//创建面析panel2
panel2.setLayout(new GridLayout(4,1));
but1.addActionListener(new handle());//设置按钮监听器
but2.addActionListener(new handle());
but3.addActionListener(new handle());
but4.addActionListener(new handle());
panel2.add(but1);panel2.add(but2);
panel2.add(but3);panel2.add(but4);
c.add(panel2,BorderLayout.EAST);
setSize(250,170);
show();
}
public class handle implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==but1){
//进行相加运算,但为什么结果不对呢
String s1=text1.getText(); String s2=text1.getText();
int a=Integer.parseInt(s1)+Integer.parseInt(s2);
String k=String.valueOf(a);//将数值型数据转化为字符型数据
text3.setText(k);
}
}
}
public static void main(String args[])
{ JWindow1 JW=new JWindow1();
JW.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{ System.exit(0);}
});
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JWindow1 extends JFrame{
JButton but1=new JButton( "+ ");JButton but2=new JButton( "- ");