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种对话框