GUI简单布局-练习(监听事件)
简单计算器实现
需求
x + y = ?
填写两个数字,点击运算符切换当前运算符,点击等号,计算结果并填充到右侧;
实现思路
- 控件使用流式布局
- 用到按钮的事件监听器
- 不同按钮使用相同监听器,用setActionCommond进行区分
代码
package com.phil.gui1;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class lessions2 {
public static void main(String[] args) {
//启动
new Caculator();
}
}
class Caculator extends Frame {
public Caculator() {
this.setLayout(new FlowLayout());
//输入框
TextField textField1 = new TextField(10);
textField1.setName("a");
this.add(textField1);
//计算符号按钮
Button button = new Button();
button.setName("o");
this.add(button);
//输入框
TextField textField2 = new TextField(10);
textField2.setName("b");
this.add(textField2);
//等于号按钮
Button equal_button = new Button("=");
equal_button.setName("e");
this.add(equal_button);
//结果框
Label label = new Label("------");
label.setBackground(Color.white);
this.add(label);
MyActionListener myActionListener = new MyActionListener(textField1, textField2, button, equal_button, label);
setVisible(true);
pack();
}
}
class MyActionListener implements ActionListener {
private TextField textField1, textField2;
private Button button1, button2;
private Label label;
private String currentOP = "+";
MyActionListener(TextField textField1, TextField textField2, Button button1, Button button2, Label label) {
this.textField1 = textField1;
this.textField2 = textField2;
this.button1 = button1;
button1.setLabel(currentOP);
button1.setActionCommand("change");
button1.addActionListener(this);
this.button2 = button2;
button2.setActionCommand("equal");
button2.addActionListener(this);
this.label = label;
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (actionCommand == "change") {
if (currentOP=="+") {
currentOP = "-";
}else if (currentOP=="-") {
currentOP = "*";
}else if (currentOP=="*") {
currentOP = "/";
}else if (currentOP=="/") {
currentOP = "+";
}
button1.setLabel(currentOP);
}else if (actionCommand == "equal"){
int value1 = Integer.parseInt(textField1.getText());
int value2 = Integer.parseInt(textField2.getText());
if (currentOP=="+") {
label.setText("" + (value1 + value2));
}else if (currentOP=="-") {
label.setText("" + (value1 - value2));
}else if (currentOP=="*") {
label.setText("" + (value1 * value2));
}else if (currentOP=="/") {
if (value2!=0) {
label.setText("" + (value1 / value2));
}else {
label.setText("err");
}
}
}
}
public Label getLabel() {
return label;
}
public void setLabel(Label label) {
this.label = label;
}
}
实现效果图

优化思路
把监听器作为MyFrame的内部类,可直接使用MyFrame的变量

浙公网安备 33010602011771号