如何在 Java 中设置 JButton 的背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2086355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:23:31  来源:igfitidea点击:

How to set a background color of a JButton in Java?

javauser-interfaceswingbackground-color

提问by Yatendra Goel

I am developing a Java Desktop Application. In it I have 4 JButtonson a JPanel. Now I want that whenever a button is clicked its background color changes to some other color (say orange) to represent that it has been clicked and the background color of all other 3 buttons reset to their default color (in case any of them had Orange background color).

我正在开发一个 Java 桌面应用程序。其中我有 4JButtonsJPanel. 现在我希望当一个按钮被点击时,它的背景颜色会变成其他颜色(比如橙色)来表示它已经被点击,并且所有其他 3 个按钮的背景颜色都重置为其默认颜色(以防它们中的任何一个有橙色)背景颜色)。

So, at one time only one button can have the orange color.

因此,一次只有一个按钮可以具有橙色。

The current approach that I have applied is that I have implemented the following code in the xxxActionPerformed()method of JButton button1

我目前应用的xxxActionPerformed()方法是在JButton button1的方法中实现了以下代码

button1.setBackground(Color.Orange);
button2.setBackground(Color.Gray);
button3.setBackground(Color.Gray);
button4.setBackground(Color.Gray);

and similarly for the rest three buttons.

其余三个按钮也类似。

Now in actual, I don't want the backgroud color as Gray (for unclicked button). Instead, I want the default background color so that the backgroud color will adjust itself to the look-and-feel of the GUI according to the end-user's platform's look-and-feel.

现在实际上,我不希望背景颜色为灰色(对于未单击的按钮)。相反,我想要默认的背景颜色,以便背景颜色会根据最终用户平台的外观和感觉调整自己以适应 GUI 的外观。

Q1. How can I get the default background color?

一季度。如何获得默认背景颜色?

Q2. Is this the correct approach to do this or Is there any other mechanism through which I can group all the four buttons in a button group so that only one can have the specified property at one time (like radio buttons)?

Q2。这是执行此操作的正确方法还是有任何其他机制可以将按钮组中的所有四个按钮分组,以便一次只有一个可以具有指定的属性(例如单选按钮)?

采纳答案by user85421

  1. just use nullto use the default color:

    button1.setBackground(Color.ORANGE);
    button2.setBackground(null);
    ...
    
  2. consider using JToggleButtons with a ButtonGroup, set the Icon and PressedIcon of the buttons. No need to change the background color.

    button1 = new JToggleButton(new ImageIcon("0.jpg"));
    button1.setSelectedIcon(new ImageIcon("1.jpg"));
    button2 = new JToggleButton(new ImageIcon("0.jpg"));
    button2.setSelectedIcon(new ImageIcon("2.jpg"));
    ...
    ButtonGroup group = new ButtonGroup();
    group.add(button1);
    group.add(button2);
    ...
    
  1. 仅用于null使用默认颜色:

    button1.setBackground(Color.ORANGE);
    button2.setBackground(null);
    ...
    
  2. 考虑使用带有 ButtonGroup 的 JToggleButtons,设置按钮的 Icon 和 PressedIcon。无需更改背景颜色。

    button1 = new JToggleButton(new ImageIcon("0.jpg"));
    button1.setSelectedIcon(new ImageIcon("1.jpg"));
    button2 = new JToggleButton(new ImageIcon("0.jpg"));
    button2.setSelectedIcon(new ImageIcon("2.jpg"));
    ...
    ButtonGroup group = new ButtonGroup();
    group.add(button1);
    group.add(button2);
    ...
    

回答by marionmaiden

Q1.: To get the GUI color of the button, just do this

Q1.: 要获取按钮的 GUI 颜色,只需执行此操作

button1.setBackground(Color.Orange);
button2.setBackground(java.awt.SystemColor.control);
button3.setBackground(java.awt.SystemColor.control);
button4.setBackground(java.awt.SystemColor.control);

With this class (java.awt.SystemColor.*), you can get the color of all elements of your user interface.

使用此类 (java.awt.SystemColor.*),您可以获得用户界面所有元素的颜色。

Q2.: I've never heard about grouping buttons. Then, I can′t answer you this one.

Q2.:我从来没有听说过分组按钮。那么,我无法回答你这个问题。

Hope it helps.

希望能帮助到你。

回答by Zappi

You can get the standard background color for buttons from the UIManager:

您可以从 UIManager 获取按钮的标准背景颜色:

button1.setBackground(UIManager.getColor("Button.background"));

As far as I know, the keys could change in different look & feels. Here is a nice webstart app that shows all available keys:

据我所知,按键可能会有不同的外观和感觉。这是一个很好的 webstart 应用程序,它显示了所有可用的键:

http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/

http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/

回答by trashgod

Here's a cross-section of "Button.background" based on this example:

这是基于此示例的“Button.background”的横截面:

*** Metal javax.swing.plaf.metal.MetalLookAndFeel 636 entries
Button.background: javax.swing.plaf.ColorUIResource[r=238,g=238,b=238]

*** Nimbus com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel 1052 entries
Button.background: com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel$NimbusProperty@60961dff

*** CDE/Motif com.sun.java.swing.plaf.motif.MotifLookAndFeel 550 entries
Button.background: javax.swing.plaf.ColorUIResource[r=174,g=178,b=195]

*** Mac OS X com.apple.laf.AquaLookAndFeel 705 entries
Button.background: com.apple.laf.AquaNativeResources$CColorPaintUIResource[r=238,g=238,b=238]

回答by Stegeta

have you looked into the decorator pattern in java you pass a button into a method which decorates it depending on whether the button is the current active one, for example if it hovered over.

你有没有研究过java中的装饰器模式,你将一个按钮传递给一个方法,该方法根据按钮是否是当前活动的按钮来装饰它,例如它是否悬停在上面。

public Jbutton decorateButton(JButton b, boolean isHoveredOver){
    if(isHoveredOver)
        b.setBackground(getContentPane().getBackground().GREEN);
    return b;
}

you call this method from the MouseEvent or ActionEvent methods and just issue a repaint() after. put all your buttons into an array or vector and loop through it passing each one in to the decorateButton method and give the initail boolean value of false then on event set it to true. This way the initial value is default and the button is then decorated upon action the buttons will appear to be acting as part of a group

你从 MouseEvent 或 ActionEvent 方法调用这个方法,然后只发出一个 repaint() 。将所有按钮放入一个数组或向量中,并循环遍历它,将每个按钮传递给decorateButton 方法,并赋予inittail 布尔值false,然后在事件发生时将其设置为true。这样,初始值是默认值,然后按钮在动作时被装饰,按钮将显示为一组的一部分

回答by Rahul

If you wish you can redesign your whole button UI

如果您希望可以重新设计整个按钮 UI

public class buttonUI extends javax.swing.plaf.basic.BasicButtonUI{

buttonUI(JButton b){
    b.setContentAreaFilled(false);
}

@Override
    public void paint(Graphics g,JComponent c){
             Graphics2D g2d = (Graphics2D) g;
             g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
             AbstractButton b = (AbstractButton) c;
             g2d.setFont(font.deriveFont(11f));
             Dimension d = b.getSize();
             FontMetrics fm = g2d.getFontMetrics();
             g2d.setColor(new Color(100,100,100));
             String caption = b.getText();
             int x = (d.width - fm.stringWidth(caption)) / 2;
             int y = (d.height + fm.getAscent()) / 2 - 2;
             g2d.drawString(caption, x, y);        
        }   }

and in your main piece of code use like

在你的主要代码中使用像

jButton1.setUI(new buttonUI(jButton1));

This how I use it .. you can have your own way too

这就是我如何使用它..你也可以有自己的方式