Java Swing界面编程(22)---事件处理:动作事件及监听处理

要想让一个button变得有意义,就必须使用事件处理。在swing的事件处理中。能够使用ActionListener接口处理button的动作事件。

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();
	}
}

程序截图:

原文地址:https://www.cnblogs.com/mfrbuaa/p/5156078.html