为Gui添加事件监听、事件源、事件

package com.demo1;

import java.awt.event.*;

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

public class SimpleGUI1B implements ActionListener{  //实现此接口。这表示SimpleGui1B是个ActionListener(事件只会通知有实现ActionListener的类)
	JButton button;	
	public static void main(String[] args) {		
		SimpleGUI1B gui = new SimpleGUI1B();
		gui.go();
	}
	public void go(){
		JFrame frame = new JFrame();          //创建frame
		button = new JButton("Click me");  //创建button
		button.addActionListener(this);    // 向按钮注册		
		frame.getContentPane().add(button);  //把button加到frame的pane上
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // 这一行程序会在Windows关闭时把程序结束掉
		frame.setSize(300, 300);  // 设定frame的大小
		frame.setVisible(true);   // 最后把frame显示出来
	}	
	@Override
	public void actionPerformed(ActionEvent e) {   // 实现interface上的方法。。。这是真正处理事件的方法!
		button.setText("I've been clicked");    //按钮会以ActionEvent对象作为参数来调用此方法		
	}
}

运行结果:

点击按钮前:


点击按钮后:








猜你喜欢

转载自blog.csdn.net/swy18929564409/article/details/80705096
今日推荐