2011年8月24日

JAVA 一個簡單的視窗範例+按鈕事件

SetConfig.java
package pbtw;


import javax.swing.*;

/**
 * @author feather
 * 
 */
public class SetConfig {

	public static void main(String[] args) {
		try {
			// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new ShowGUI();
			}
		});
	}

}

ShowGUI.java
package pbtw;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ShowGUI extends JFrame {

	private static final long serialVersionUID = 1503853650869214906L;

	JButton button1 = new JButton("Hello World1");
	JButton button2 = new JButton("Hello World2");

	public ShowGUI() {

		setDefaultLookAndFeelDecorated(true);
		setTitle("一個簡單的視窗範例+按鈕事件");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container cp = getContentPane();
		cp.setLayout(new FlowLayout());

		setSize(300, 300);
		// frame.pack();
		setLocationRelativeTo(null);// 這會讓視窗置中
		setVisible(true);

		// ---------------- 比較簡單但是這種方法用多了整個架構容易混淆 ------------
		// JButton button1 = new JButton("Hello World");
		button1.addActionListener(new ActionListener() {// bt1事件的動作
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "按鈕1被點擊");
			}
		});
		
		cp.add(button1);
		cp.add(button2);

		// 內部類別 Button2Handler
		class Button2Handler implements ActionListener {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "按鈕2被點擊");
			}
		}

		button2.addActionListener(new Button2Handler());// 實體化Button2Handler這個內部類別來監聽

	}

}

沒有留言:

張貼留言