- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.*;
- import javax.swing.text.BadLocationException;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- public class CALC implements ActionListener{
- public static void main(String[] args)
- {
- // TODO 自動產生的方法 Stub
- CALC calc = new CALC();
- }
- @Override
- public void actionPerformed(ActionEvent e)
- {
- // TODO 自動產生的方法 Stub
- if(e.getSource()==bt1)
- {
- tf2.setText("面積為 "+Double.parseDouble(tf1.getText())*3.3058+" sqmeter.");
- }
- if(e.getSource()==bt2)
- {
- tf1.setText("");
- tf2.setText("");
- }
-
- }
-
- private JFrame fm;
- private JLabel lb1;
- private JLabel lb2;
- private JTextField tf1;
- private JTextField tf2;
- private JButton bt1;
- private JButton bt2;
-
- CALC()
- {
- fm=new JFrame("土地面積計算");
- lb1=new JLabel("1坪=3.3058sqmeter");
- lb2=new JLabel("輸入坪數:");
- tf1=new JTextField();
- tf1.addKeyListener(new KeyAdapter() {
- @Override
- public void keyReleased(KeyEvent arg0) {
- int kc=arg0.getKeyCode();
-
- if(kc==8 || 96<= kc && kc<=105 || kc==110)
- {
- System.out.println("y");
- }
- else
- {
- int length = tf1.getText().length();
- String str;
- try
- {
- System.out.println("n");
- str = tf1.getText(0, --length);
- tf1.setText(str);
- }
- catch (BadLocationException e)
- {
- // TODO 自動產生的 catch 區塊
- e.printStackTrace();
- }
-
-
- }
- }
- });
-
- tf2=new JTextField();
- bt1=new JButton("確定");
- bt2=new JButton("清除");
-
- lb1.setBounds(45, 10, 215, 30);
- lb2.setBounds(10, 40, 60, 40);
-
- tf1.setBounds(70, 45, 125, 30);
- tf2.setBounds(10, 85, 185, 40);
- tf1.setEditable(true);
- tf2.setEditable(false);
- tf1.addActionListener(this);
- tf2.addActionListener(this);
-
- bt1.setBounds(10, 135, 92, 25);
- bt2.setBounds(105, 135, 92, 25);
- bt1.addActionListener(this);
- bt2.addActionListener(this);
-
- fm.setBounds(100, 100, 220, 200);
- fm.setVisible(true);
- fm.setResizable(true);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.getContentPane().setLayout(null);
- fm.getContentPane().add(tf1);
- fm.getContentPane().add(tf2);
- fm.getContentPane().add(lb1);
- fm.getContentPane().add(lb2);
- fm.getContentPane().add(bt1);
- fm.getContentPane().add(bt2);
- }
- }
複製代碼 |