SWUST--Java實驗(四) 簡單計算器
阿新 • • 發佈:2019-02-17
import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Demo extends JFrame { JPanel jp1 = new JPanel(); JPanel jp2 = new JPanel(); JPanel jp3 = new JPanel(); JButton bt1 = new JButton("+"); JButton bt2 = new JButton("-"); JButton bt3 = new JButton("*"); JButton bt4 = new JButton("/"); JTextField jf1 = new JTextField(); JTextField jf2 = new JTextField(); JTextField jf3 = new JTextField("我來顯示"); JLabel jl1 = new JLabel("運算結果:"); JLabel jl2 = new JLabel("+"); public Demo() { setBounds(100,100,200,200); setTitle("簡易Windows計算器"); jf1.setColumns(6); jf2.setColumns(6); jf3.setColumns(12); jp1.setLayout(new GridLayout(2,2)); jp1.add(bt1); jp1.add(bt2); jp1.add(bt3); jp1.add(bt4); jp2.setLayout(new FlowLayout()); jp2.add(jl1); jp2.add(jf3); jp3.setLayout(new FlowLayout()); jp3.add(jf1); jp3.add(jl2); jp3.add(jf2); setLayout(new BorderLayout()); //控制佈局 add("South",jp1); add("North",jp3); add("Center",jp2); bt1.addActionListener(new ActionListener() { //按鈕'+'加監聽 @Override public void actionPerformed(ActionEvent arg0) { jl2.setText("+"); //設定顯示的符號 String x1 = jf1.getText(); //賦值鍵入的資料 String x2 = jf2.getText(); int s1 = Integer.parseInt(x1); //轉換為整數 int s2 = Integer.parseInt(x2); int s3 = s1 + s2; //運算 jf3.setText(s3+""); //中間的文字框顯示結果 } }); bt2.addActionListener(new ActionListener() { //同上 @Override public void actionPerformed(ActionEvent arg0) { jl2.setText("-"); String x1 = jf1.getText(); String x2 = jf2.getText(); int s1 = Integer.parseInt(x1); int s2 = Integer.parseInt(x2); int s3 = s1 - s2; jf3.setText(s3+""); } }); bt3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { jl2.setText("*"); String x1 = jf1.getText(); String x2 = jf2.getText(); int s1 = Integer.parseInt(x1); int s2 = Integer.parseInt(x2); int s3 = s1 * s2; jf3.setText(s3+""); } }); bt4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { jl2.setText("/"); String x1 = jf1.getText(); String x2 = jf2.getText(); int s1 = Integer.parseInt(x1); int s2 = Integer.parseInt(x2); int s3 = s1 / s2; jf3.setText(s3+""); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new Demo(); } }