1. 程式人生 > >Java GUI之事件監聽與處理

Java GUI之事件監聽與處理

事件監聽和處理的根本技術,是回撥。甲方提供介面,乙方實現介面並呼叫相應方法。

package com.sinosuperman.driver;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class MainBench {
	public static void main(String[] args) {
		JFrame frame = new MyFrame();
	}
}

class MyFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	Toolkit tk = Toolkit.getDefaultToolkit();
	Dimension d = tk.getScreenSize();
	JPanel panel;
	public MyFrame() {
		panel = new MyPanel();
		this.add(panel);
		this.setSize((int) d.getWidth() / 2, (int) d.getHeight() / 2);
		this.setLocation((int) (d.getWidth() - this.getWidth()) / 2, (int) (d.getHeight() - this.getHeight()) / 2);
		this.setResizable(false);
		this.setVisible(true);
	}
}

class MyPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = 5263963243638550398L;
	JButton okBtn;
	JButton exitBtn;
	public MyPanel() {
		this.setLayout(new FlowLayout(FlowLayout.CENTER));
		okBtn = new JButton("OK");
		exitBtn = new JButton("Exit");
		okBtn.addActionListener(this);
		exitBtn.addActionListener(this);
		this.add(okBtn);
		this.add(exitBtn);
	}
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if (source == okBtn) {
			JOptionPane.showMessageDialog(null, "You click the OK Button.");
		} else {
			JOptionPane.showMessageDialog(null, "You click the Exit Button.");
			System.exit(0);
		}
	}
}