(1) 建立一個 Java 類別Ex14Class 要有main()函數
(2) 使用jframe
import java.awt.EventQueue;
import javax.swing.*;
private JFrame frame;
public Ex14Class() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Java Swing");
frame.setLayout(null);//不使用版面配置
}
(3) 修改main()
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ex14Class window = new Ex14Class();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
(4) 在frame視窗中加入一個按鍵JButton
private JButton btn;
btn = new JButton("Click me!");
btn.addActionListener(listener);
btn.setBounds(180, 100, 100, 50);
frame.add(btn);
(5) 增加按鍵的事件處理器(ActionListener)
建立一個 Java 類別Ex14ActionListener不需main()函數
import java.awt.event.*;
import javax.swing.*;
public class Ex14ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");
}
}
參考資料
Swing hello world
http://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.javag實作ActionListener
http://www.dotblogs.com.tw/tiffany/archive/2012/05/31/72515.aspx