面向对象经典应用 变换界面的颜色 (Java经典编程案例)

案例:在一个界面上定义三个按钮,点击不同的按钮,可以为面板设置不同的颜色。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Example extends JFrame {

    private JPanel contentPane;

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Example frame = new Example();
                    frame.setVisible(true);
                    frame.contentPane.requestFocus();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    //Create the frame.
    public Example() {
        setTitle("普通内部类的简单应用");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 500, 200);
        contentPane = new JPanel();
        contentPane.setLayout(null);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        final JButton redButton = new JButton();
        redButton.setText("红色");
        redButton.setBounds(15, 20, 82, 30);
        redButton.addActionListener(new ColorAction(Color.RED));
        contentPane.add(redButton);

        final JButton greenButton = new JButton();
        greenButton.setText("绿色");
        greenButton.setBounds(100, 20, 82, 30);
        greenButton.addActionListener(new ColorAction(Color.GREEN));
        contentPane.add(greenButton);

        final JButton blueButton = new JButton();
        blueButton.setText("蓝色");
        blueButton.setBounds(185, 20, 82, 30);
        blueButton.addActionListener(new ColorAction(Color.BLUE));
        contentPane.add(blueButton);
    }

    private class ColorAction implements ActionListener {

        private Color background;

        public ColorAction(Color background) {
            this.background = background;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            contentPane.setBackground(background);
        }
    }
}

执行结果如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/cui_yonghua/article/details/93617508