Java Swing界面編程(22)---事件處理:動作事件及監聽處理

要想讓一個按鈕變得有意義,就必須使用事件處理。在swing的事件處理中,可以使用ActionListener接口處理按鈕的動作事件。

package com.beyole.util;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

class ActionHandle {
	private JFrame frame = new JFrame("Crystal");// 聲明一個窗體對象
	private JButton button = new JButton("顯示");
	private JLabel label = new JLabel();
	private JTextField text = new JTextField(10);
	private JPanel panel = new JPanel();

	public ActionHandle() {
		Font font = new Font("Serief", Font.ITALIC + Font.BOLD, 28);// 設置字體
		label.setFont(font);// 設置標籤字體
		label.setText("等待用戶輸入信息");// 設置默認顯示文字
		button.addActionListener(new ActionListener() { // 採用內部匿名類

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == button) {// 判斷觸發源是否爲按鈕
					label.setText(text.getText());// 將文本文字設置到標籤
				}
			}
		});// 加入動作監聽
		frame.addWindowListener(new WindowAdapter() {// 加入窗口監聽
			public void windowClosing(WindowEvent arg0) {
				System.exit(1);// 系統退出
			}
		});
		frame.setLayout(new GridLayout(2, 1));// 設置窗體佈局
		panel.setLayout(new GridLayout(1, 2));// 設置面板佈局
		panel.add(text);// 將文本域加入到面板
		panel.add(button);// 將按鈕加入到面板
		frame.add(panel);// 將面板加入到窗體
		frame.add(label);// 將標籤加入到窗體
		frame.pack();// 根據組件自動調整大小
		frame.setVisible(true);// 顯示窗體
	}
}

public class MyActionEventDemo {
	public static void main(String[] args) {
		new ActionHandle();
	}
}

程序截圖:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章