整个代码的结构就是一个启动一个类 计算器类里通过组合以及内部类最大化简化代码
package GUI;
import Myutil.Constant;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class EasyCalculator {
public static void main(String[] args) {
new Calculator().loadFrame();
}
}
class Calculator extends Frame{
TextField num1,num2,num3;
public void loadFrame(){
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
Label label = new Label("+");
Button button = new Button("=");
setLayout(new FlowLayout());
setBounds(Constant.FRAME_X,Constant.FRAME_Y,Constant.FRAME_WIDTH,Constant.FRAME_HEIGHT);
button.addActionListener(new MyCal_ActionListener());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
pack();
setVisible(true);
}
private class MyCal_ActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
int n_1 = Integer.parseInt(num1.getText());
int n_2 = Integer.parseInt(num2.getText());
String s = Integer.toString(n_1 + n_2);
num3.setText(s);
}
}
}
常量类(好习惯封装常量类)
package Myutil;
import java.awt.*;
public class Constant {
public static final int FRAME_WIDTH = 750;
public static final int FRAME_HEIGHT =400;
public static final int SCREEN_W = Toolkit.getDefaultToolkit().getScreenSize().width;
public static final int SCREEN_H = Toolkit.getDefaultToolkit().getScreenSize().height;
public static final int FRAME_X = SCREEN_W-FRAME_WIDTH>>1;
public static final int FRAME_Y = SCREEN_H-FRAME_HEIGHT>>1;
}
简单计算器的实现(组合内部类)
|