Java如何获取组件的JFrame?

该演示给出了有关如何获取JFrame组件的示例。在此示例中,我们尝试JFrame从按钮操作侦听器事件获取。为了得到JFrame我们使用的SwingUtilities.getRoot()方法,它将在小程序的下面返回组件树的根组件,该小程序是一个JFrame。

除了获取之外JFrame,在此程序中,我们还执行一些细小的操作,例如,每当用户按下“更改框架颜色”按钮时,将框架背景颜色更改为随机颜色。

package org.nhooo.example.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.HeadlessException;

public class GetFrameDemo extends JFrame {
    public GetFrameDemo() throws HeadlessException {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GetFrameDemo().setVisible(true));
    }

    private void initialize() {
        this.setSize(400, 100);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.setLayout(new FlowLayout(FlowLayout.CENTER));

        final JLabel rLabel = new JLabel("r: ");
        final JLabel gLabel = new JLabel("g: ");
        final JLabel bLabel = new JLabel("b: ");

        JButton button = new JButton("Change Frame Background Color");
        button.addActionListener(e -> {
            Component component = (Component) e.getSource();

            // 返回当前组件树的根组件
            JFrame frame = (JFrame) SwingUtilities.getRoot(component);

            int r = (int) (Math.random() * 255);
            int g = (int) (Math.random() * 255);
            int b = (int) (Math.random() * 255);

            rLabel.setText("r: " + r);
            gLabel.setText("g: " + g);
            bLabel.setText("b: " + b);

            frame.getContentPane().setBackground(new Color(r, g, b));
        });

        this.getContentPane().add(button);
        this.getContentPane().add(rLabel);
        this.getContentPane().add(gLabel);
        this.getContentPane().add(bLabel);
    }
}