java监听器用法(二):窗口监听器
生活随笔
收集整理的这篇文章主要介绍了
java监听器用法(二):窗口监听器
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonFrame extends JFrame implements ActionListener{//窗口直接实现了监听接口,整个窗口做监听器private static final long serialVersionUID = 1L;private JPanel buttonPanel;private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;JButton yellowButton ,blueButton,redButton;public ButtonFrame(){ setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 创建按钮对象yellowButton = new JButton("Yellow");blueButton = new JButton("Blue");redButton = new JButton("Red");buttonPanel = new JPanel();// 添加按钮到画板buttonPanel.add(yellowButton);buttonPanel.add(blueButton);buttonPanel.add(redButton); add(buttonPanel);// 为每个按钮设置监听器,这里要用this,表示窗口本身yellowButton.addActionListener(this);blueButton.addActionListener(this);redButton.addActionListener(this);}@Overridepublic void actionPerformed(ActionEvent e) {// //窗口做监听器,要使用e.getSource()方法判断触发事件的事件源if(e.getSource()==yellowButton)buttonPanel.setBackground(Color.YELLOW);if(e.getSource()==blueButton)buttonPanel.setBackground(Color.BLUE);if(e.getSource()==redButton)buttonPanel.setBackground(Color.RED); }
}
总结
以上是生活随笔为你收集整理的java监听器用法(二):窗口监听器的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Java监听器用法(三):外部类监听器
- 下一篇: JOptionPane的常用4种对话框