面向对象经典应用 变换界面的颜色 (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);
        }
    }
}

执行结果如下图:
面向对象经典应用 变换界面的颜色 (Java经典编程案例)_第1张图片

你可能感兴趣的:(Java经典编程案例)