java實現計算器and圖形介面
阿新 • • 發佈:2019-01-05
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//AWT實現
public class AWTCalculation{
//將視窗中的元件定義為屬性
private Frame frame; //定義窗體
public TextField field; //定義文字框
private Button[] allButtons; //定義按鈕陣列
//在構造方法中建立元件
public AWTCalculation(){
frame = new Frame("AWT計算器");
field = new TextField(20);
//建立計算機按鈕
allButtons = new Button[20];
String str = "←^√±789÷456×123-0.=+";
for(int i = 0; i < str.length(); i++){
allButtons[i] = new Button(str.substring(i,i+1));
}
}
//初始化視窗,設定佈局
private void init(){
//frame的北部面板:預設FlowLayout佈局
Panel northPanel = new Panel();
northPanel.add(field);
//frame的中部面板:設定GridLayout佈局
Panel centerPanel = new Panel();
GridLayout grid = new GridLayout(5 ,4,8,8);
centerPanel.setLayout(grid);
//將按鈕新增至中部面板
for(int i = 0;i < allButtons.length; i++){
centerPanel.add(allButtons[i]);
}
//將面板新增至視窗
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
}
//設定視窗顯示屬性
public void showMe(){
init();
addEventHandler();
frame.pack();
frame.setLocation(500,400); //窗口出現的位置
frame.addWindowListener(new WindowCloseHanDler());
frame.setResizable(false); //禁止改變視窗大小
frame.setBackground(Color.PINK);
frame.setVisible(true); //設定窗體可見
}
//事件監聽器 --- 關閉視窗
private class WindowCloseHanDler extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
//功能實現部分
public void addEventHandler(){ //新增監聽
for(int i = 0; i < allButtons.length; i++){ //按鈕區監聽
allButtons[i].addActionListener(new CalculateActionHandler());
}
}
//利用內部類繼承ActionListener 實現 ActionPerformed 方法
class CalculateActionHandler implements ActionListener{
double op1 = 0,op2 = 0; //儲存兩個運算元
String operator = "";
boolean flag = true;
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand(); //按鈕上的文字
if("0123456789.".indexOf(command) != -1){ //數字按鈕或小數點按鈕
if(flag){ //如果之前處理的是等號,開始組織新的運算元
field.setText(command);
flag = false;
}else{ //否則繼續拼接運算元
field.setText(field.getText()+command);
}
}else if( "← ^ √ ± ÷ × - +".indexOf(command) != -1 ){ //1取文字框中的資料:第一個運算元
if(command.equalsIgnoreCase("←")){ //如果是清除,則歸零
op1 = 0;
field.setText("");
}else if(command.equalsIgnoreCase("√")) {
operator = command;
field.setText(command);
}else {
op1 = Double.valueOf(field.getText());
//2 記下運算子
operator = command;
//3 清空文字框
field.setText(command);
}
flag = true;
}else if( command.equalsIgnoreCase("=") ){ //等號按鈕
double res = 0;
String text = field.getText();
if(text.length()>0){
op2 = Double.valueOf(text);
switch(operator) {
case "+":
res = op1 + op2;
break;
case "-":
res = op1 - op2;
break;
case "×":
res = op1 * op2;
break;
case "÷":
res = op1 / op2;
break;
default:
break;
}
field.setText(String.valueOf(res));
}
flag = true;
}
}
}
public static void main(String []args){
new AWTCalculation().showMe();
}
}