標籤:java簡單計算機 java計算機
自己寫著寫著 忘了。。順便看看書 哈哈~~
Window:
import java.awt.*;public class Window {public static void main(String args[]){WindowInit win=new WindowInit();Container con=win.getContentPane();con.setBackground(Color.green);}}
WindowInit:
import java.awt.*;import javax.swing.*;public class WindowInit extends JFrame{JTextField input1,input2;JComboBox choicefuhao;JButton button;JTextArea showarea;OperatorListener operator;ComputerListener computer;public WindowInit(){init();setBounds(100,100,429,329);setTitle("計算機");setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}void init(){setLayout(new FlowLayout());input1=new JTextField(5);input2=new JTextField(5);button=new JButton("確定");choicefuhao=new JComboBox();choicefuhao.addItem("請選擇符號");choicefuhao.addItem("+");choicefuhao.addItem("-");choicefuhao.addItem("*");choicefuhao.addItem("/");showarea=new JTextArea(9,36);operator=new OperatorListener();computer=new ComputerListener();operator.setChoicefuhao(choicefuhao);operator.setWorktogether(computer);computer.setInput1(input1);computer.setInput2(input2);computer.setTextArea(showarea);button.addActionListener(computer);//感覺這裡也應該加上
//input1.addActionListener,input2.addActionListenerchoicefuhao.addItemListener(operator);add(input1);add(choicefuhao);add(input2);add(button);add(showarea);}}
OperatorListener:
import javax.swing.*;
import java.awt.event.*;
public class OperatorListener implements ItemListener{
JComboBox choicefuhao;
ComputerListener worktogether;
public void setChoicefuhao(JComboBox e){
choicefuhao=e;
}
public void setWorktogether(ComputerListener e){
worktogether=e;
}
public void itemStateChanged(ItemEvent e){
String fuhao=choicefuhao.getSelectedItem().toString();
worktogether.setfuhao(fuhao);
}
}
ComputerListener:
import java.awt.event.*;import javax.swing.*;public class ComputerListener implements ActionListener{JTextField input1,input2;JButton button;JTextArea showarea;String fuhao;public void setInput1(JTextField e){input1=e;}public void setInput2(JTextField e){input2=e;}public void setfuhao(String e){fuhao=e;}public void setTextArea(JTextArea e){showarea=e;}public void actionPerformed(ActionEvent e){double num1=Double.parseDouble(input1.getText());double num2=Double.parseDouble(input2.getText());double result=0;if(fuhao.equals("+"))result=num1+num2;else if(fuhao.equals("-"))result=num1-num2;else if(fuhao.equals("*"))result=num1*num2;else result=num1/num2;showarea.append(num1+fuhao+num2+"="+result+"\n");}}
這是運行結果:
java簡單計算機