编程实现:有四个按钮,分别为加 减 乘 除;窗口中又三个文本行,单击任意一按钮,将两个文本行的数据进行相应运算,在第单个文本行中显示结果。
窗口如图所示 例:点击*出现计算结果;
package Chapter;import java.awt.*;
import java.awt.event.*;public class Scomputer extends Frame{public
Scomputer(){
this.setSize(400,400);
this.setLayout(null);
this.setTitle("简单计算器");
this.setVisible(true);
this.setLayout(new FlowLayout(FlowLayout.LEFT,20,20));
Button sum=new Button("+");
Button sub=new Button("-");
Button mul=new Button("*");
Button divi=new Button("/");
TextField txt1=new TextField();
TextField txt2=new TextField();
TextField txt3=new TextField();
txt3.setBounds(5, 5, 30, 20);
this.add(divi);
this.add(mul);
this.add(sub);
this.add(sum);
this.add(txt1);
this.add(txt2);
this.add(txt3);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
sum.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i=Integer.parseInt(txt1.getText());
int j=Integer.parseInt(txt2.getText());
txt3.setText(String.valueOf(i+j));
}
});
sub.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i=Integer.parseInt(txt1.getText());
int j=Integer.parseInt(txt2.getText());
txt3.setText(String.valueOf(i-j));
}
});
mul.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i=Integer.parseInt(txt1.getText());
int j=Integer.parseInt(txt2.getText());
txt3.setText(String.valueOf(i*j));
}
});
divi.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i=Integer.parseInt(txt1.getText());
int j=Integer.parseInt(txt2.getText());
txt3.setText(String.valueOf(i/j));
}
});
}
public static void main(String[] args){
new Scomputer();
}
}
本文介绍了一个使用Java Swing实现的简易计算器程序。该程序通过图形用户界面接收用户输入的两个数值,并根据用户选择的操作(加、减、乘、除)显示计算结果。文中详细展示了如何创建按钮、文本框并为它们添加事件监听器。
2022

被折叠的 条评论
为什么被折叠?



