- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JTextField;
- import javax.swing.text.BadLocationException;
- import java.awt.Color;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- public class Main implements ActionListener {
- public static void main(String[] args) {
- Main app=new Main();
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==btn1)
- {
- tf2.setText("面積為: "+Float.parseFloat(tf1.getText())*3.3058+"平方公尺");
- }
- if(e.getSource()==btn2)
- {
- tf1.setText("");
- tf2.setText("");
- }
- }
- public JFrame fm;
- private JTextField tf1, tf2;
- private JButton btn1, btn2;
- private JLabel lb1, lb2;
- Main() {
- fm = new JFrame("JTextField配置練習");
- tf1 = new JTextField();
- tf1.addKeyListener(new KeyAdapter() {
- public void keyReleased(KeyEvent e) {
- int code=e.getKeyCode();
- if(code>96 && code<105)
- {
- System.out.println(code);
- }
- else
- {
- int temp=tf1.getText().length();
- try {
- String str=tf1.getText(0, --temp);
- tf1.setText(str);
- } catch (BadLocationException e1) {
- // TODO 自動產生的 catch 區塊
- e1.printStackTrace();
- }
- }
- }
- });
- tf1.setBackground(Color.WHITE);
- tf2 = new JTextField();
- tf2.setBackground(Color.WHITE);
- lb1 = new JLabel("1坪=3.3058平方公尺", JLabel.CENTER);
- lb2 = new JLabel("輸入坪數:");
- btn1 = new JButton("確定");
- btn2 = new JButton("清除");
- tf1.setBounds(70, 45, 134, 30);
- tf1.addActionListener(this);
- tf2.setBounds(10, 82, 195, 40);
- tf2.addActionListener(this);
- tf2.setEditable(false);
- lb1.setBounds(0, 10, 215, 30);
- lb2.setBounds(10, 40, 60, 40);
- btn1.setBounds(10, 135, 92, 25);
- btn1.addActionListener(this);
- btn2.setBounds(112, 135, 92, 25);
- btn2.addActionListener(this);
-
- fm.setBounds(100, 100, 227, 206);
- 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(btn1);
- fm.getContentPane().add(btn2);
- }
- }
複製代碼 |