Java 按下按钮时如何更改按钮文本颜色和背景颜色

Java 按下按钮时如何更改按钮文本颜色和背景颜色,java,swing,synth,Java,Swing,Synth,我试图在按下鼠标按钮时,使用Java中的Swing UI更改按钮的背景色和文本(前景)色。我的主要课程非常简单明了: public class Main { public static void main(String[] args) { SynthLookAndFeel laf = new SynthLookAndFeel(); try { laf.load(Main.class.getResourceAsStream(&qu

我试图在按下鼠标按钮时,使用Java中的Swing UI更改按钮的背景色和文本(前景)色。我的主要课程非常简单明了:

public class Main {


    public static void main(String[] args) {
        SynthLookAndFeel laf = new SynthLookAndFeel();
        try {
            laf.load(Main.class.getResourceAsStream("/styles.xml"), Main.class);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            UIManager.setLookAndFeel(laf);
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }

        JFrame frame = new JFrame("Not hello world");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(300, 300);
        frame.setLocation(50, 50);
        frame.setLayout(new FlowLayout());

        frame.add(new JButton("Button 1"));
        frame.add(new JButton("Button 2"));
        frame.add(new JButton("Button 3"));

        frame.setVisible(true);


    }
}
加载的XML Synth样式文件如下所示:

<synth>
    <style id="basicStyle">
        <font name="Verdana" size="16"/>
        <state>
            <color value="#eeeeee" type="BACKGROUND"/>
            <color value="#000000" type="FOREGROUND"/>
        </state>

    </style>
    <bind style="basicStyle" type="region" key=".*"/>

<style id ="button_style">
    <state value="PRESSED">
        <color value="#666666" type="FOREGROUND" />
        <color value="#aaaaaa" type="BACKGROUND" />
    </state>
</style>
<bind style="button_style" type="region" key="button"/>

但我得到的只是屏幕上有黑色文本和灰色背景的按钮。按下按钮时,不会发生任何情况:


有什么方法可以实现这样的行为吗?

您的
Synth
文件中存在一些问题:

  • 它不是用

  • 如果不在其中设置
    opaque=“true”
    ,默认情况下,
    JButton
    将是透明的(即,您的背景将不可见)

  • 我不完全确定原因,但要在状态更改时更改前景字体颜色,您需要使用
    TEXT\u foreground
    而不是
    foreground

  • 我更改了文件中的一些颜色,因为它们不太可见,但您的文件应该看起来像:

    <synth>
        <style id="basicStyle">
            <font name="Verdana" size="16" />
            <state>
                <color value="#eeeeee" type="BACKGROUND" />
                <color value="#000000" type="FOREGROUND" />
            </state>
    
        </style>
        <bind style="basicStyle" type="region" key=".*" />
    
        <style id="button_style">
            <opaque value="true" />
            <insets top="4" left="4" right="4" bottom="4" />
            <state>
                <color value="blue" type="TEXT_FOREGROUND" />
                <color value="#ffffff" type="BACKGROUND" />
            </state>
            <state value="PRESSED">
                <color value="white" type="TEXT_FOREGROUND" />
                <color value="#aaaaaa" type="BACKGROUND" />
            </state>
        </style>
        <bind style="button_style" type="region" key="button" />
    </synth>