JButton 不会显示背景颜色

JButton will not display background color

所以我正在编写一个程序,我最终希望 JButton 在按下时改变颜色。到目前为止,这是我的困境:

-尽管切换了 setOpaque() 和 setContentAreaFilled() 的 true/false,但我无法获取当前已设置为显示背景颜色的 JButton。我希望能够在尝试添加 ActionListener 之前执行此操作。

-我想使用类似于 JToggleButton() 的方法来更改颜色,但是我想只使用背景而不是图标来执行此操作。

我正在使用 mac,我想知道它是否与默认按钮设置有关,但我不知道如何 change/override 这些。

我会post截图,可惜我的声望还不够高。

这是我得到的示例:

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

public class Example extends JFrame {

  public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }

  public static void createAndShowGUI() {

    JFrame main = new JFrame("Example");
    JPanel content = new JPanel();
    JButton button = new JButton("Press");

    button.setBackground(Color.orange);
    button.setContentAreaFilled(false);
    button.setOpaque(true);

    content.add(button);

    main.setContentPane(content);
    main.setVisible(true);
    main.setSize(40,60);
    main.setLocation(500, 200);
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

}

对于那些(可能在 windows 或 linux 平台上)看不到我在说什么的人,按钮出现了,按钮后面的布局(不是边框或JPanel,只是按钮周围的一个小矩形)根据指定的颜色着色。

提前感谢您的宝贵时间。

此外,我知道在 ActionListener 内部,getSource() 方法将 return 与按钮关联的文本。有没有什么方法可以使用类似的方法从 ActionListener 内部更改按钮的颜色,或者这个想法只是对可以以更简单的方式完成的事情的冗余。

非常感谢。

我想你想尝试一下外观和感觉。 尝试

button.setUI(new MetalButtonUI());

或尝试为按钮 UI 支持的其他背景颜色。

I would eventually like a JButton to change color when pressed

here are two different ways (note JButton has an arrays of colors in UIManager)

  • 覆盖 ButtonModel 的事件(ChangeListener 或实现相同的方法,例如 JButtons 中的 isPressed、isArmed API),加速器对鼠标和 KeyEvens(选择或 focusInWindow)有效

  • 覆盖 BasicsButtonUI(对于实际项目)

I am using a mac, and I'm wondering if it has something to do with the default button settings, but I don't know how to change/override these.

我认为button.setOpaque(true);没有必要。

删除它,或将其更改为:button.setOpaque(false); 看看发生了什么