如何更改JCheckBox中对焦环的颜色?

时间:2014-06-21 10:15:45

标签: java swing jcheckbox

我们的Swing GUI有一个带白色控件的黑色面板。但是,面板上的JCheckBox实例始终将对焦环显示为黑色。渲染聚焦环时似乎忽略了前景色。这是一个示例,我将内容窗格背景设置为灰色,以便可以看到对焦环:

enter image description here

以下是我使用的代码:

import javax.swing.*;
import java.awt.*;

public class ScratchSpace {

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JCheckBox checkBox = new JCheckBox("Hello cruel world");
                checkBox.setForeground(Color.WHITE);
                checkBox.setOpaque(false);

                JPanel contentPane = new JPanel();
                contentPane.setOpaque(true);
                contentPane.setBackground(new Color(0.5f, 0.5f, 0.5f));
                contentPane.add(checkBox);

                JFrame frame = new JFrame();
                frame.setContentPane(contentPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

如何告诉JCheckBox以特定颜色渲染聚焦环?理想情况下,它会使用控件的前景色。

1 个答案:

答案 0 :(得分:4)

您可以尝试更改外观属性CheckBox.focus,请注意,这样做会影响所有JCheckBox ...

enter image description here

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestCheckBox {

    public static void main(String[] args) {
        new TestCheckBox();
    }

    public TestCheckBox() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                UIManager.put("CheckBox.focus", Color.RED);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(new JCheckBox("Hello world"));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}