首页 > 解决方案 > 按下按钮时如何更改按钮文本颜色和背景颜色

问题描述

我正在尝试使用 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"/>

但我得到的只是屏幕上带有黑色文本和灰色背景的按钮。按下按钮时,没有任何反应:

在此处输入图像描述

我有什么办法可以实现这种行为?

标签: javaswingsynth

解决方案


Synth您的文件中有一些问题:

  1. 它没有关闭</synth>

  2. 如果您没有opaque="true"在其中设置,默认情况下您JButton将是透明的(即您的背景将不可见)。

  3. 我不完全确定为什么,但是要使前景字体颜色在状态更改时更改,您需要使用TEXT_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>

在此处输入图像描述 在此处输入图像描述


推荐阅读