Java学习之路-GUI-用Frame实现3种事件处理方式

用三种不同的事件处理方式,实现点击按钮改变背景颜色和关闭窗口的功能。
package GUI;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Random;

public class FrameTest1 extends Frame implements ActionListener{

    Button button1;
    Button button2;
    Button button3;

    public FrameTest1(){
        this.setTitle("改变颜色");
        this.setSize(400,300);
        this.setLayout(new FlowLayout( ));
        button1 = new Button("匿名");
        button2 = new Button("内部类");
        button3 = new Button("接口");

        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                changeColor();
            }
        });

        buttonListener bl = new buttonListener();
        button2.addActionListener(bl);

        button3.addActionListener(this);

        this.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent windowEvent) {

            }

            @Override
            public void windowClosing(WindowEvent windowEvent) {
                System.exit(0);
            }

            @Override
            public void windowClosed(WindowEvent windowEvent) {

            }

            @Override
            public void windowIconified(WindowEvent windowEvent) {

            }

            @Override
            public void windowDeiconified(WindowEvent windowEvent) {

            }

            @Override
            public void windowActivated(WindowEvent windowEvent) {

            }

            @Override
            public void windowDeactivated(WindowEvent windowEvent) {

            }
        });

        this.add(button1);
        this.add(button2);
        this.add(button3);

        this.setResizable(false);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        changeColor();
    }

    class buttonListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            changeColor();
        }
    }

    public void changeColor(){
        Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        Color c = new Color(r, g, b);
        this.setBackground(c);
    }

    public static void main (String[] args){
        new FrameTest1();
    }
}
按讚

發佈留言

電子郵件地址不會被公開。必填項已用 * 標註