java - Swing JButton 中的默认属性(颜色)(默认)

标签 java swing jbutton

我尝试获取 Swing JButton 中的背景颜色(默认)。返回的颜色是 RGB (238,238,238),但这并不完全是我需要的。 将背景颜色更改为其他颜色后,如何将背景颜色恢复为默认颜色?

JPanel panelButtons = new JPanel();
JButton button_01 = new JButton("01");
panelButtons.add(button_01);

默认 JButton:

enter image description here

在我的代码的特定条件下,我定义了:

button_01.setBackground(Color.BLACK);
button_01.setForeground(Color.GREEN);

背景颜色和前景已更改的 JButton:

enter image description here

在我的代码的另一个条件下,我需要将 JButton button_01 的背景颜色返回到旧配置:

我尝试将背景设置为nullUIManager.getColor("panelButtons.background"):

button_01.setBackground(null);
button_01.setForeground(Color.BLACK);

或者

button_01.setBackground(UIManager.getColor("panelButtons.background"));
button_01.setForeground(Color.BLACK);

结果是一样的:

enter image description here

如何将 JButton button_01 返回到默认主题颜色?

最佳答案

How can I return the background color to default after I changed the background color to another color ?

尝试将 JButton 的背景设置为 null。例如:

myButton.setBackground(null);
<小时/>

例如:

import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class ChangeButtonColor {

   private static void createAndShowGui() {
      final JButton myButton = new JButton(new AbstractAction("Press Me To Swap Colors") {
         private boolean flag = true;

         @Override
         public void actionPerformed(ActionEvent e) {
            Color c = flag ? Color.RED : null;
            ((AbstractButton) e.getSource()).setBackground(c);
            flag = !flag;
         }
      });

      JPanel mainPanel = new JPanel();
      mainPanel.add(myButton);

      JFrame frame = new JFrame("GUI");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

关于java - Swing JButton 中的默认属性(颜色)(默认),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31699373/

相关文章:

java - 这种方法有什么问题 - (在 Jlist 中添加元素)?

java - 如何检查 JButton 是否已按下?如果 isEnable() 不起作用?

Java 多按钮 Action

java - Netbeans 设计 View 中的动态按钮

java - 如何将巨大的字符串数据从javascript传递到java Action 类?

java - 使用正则表达式删除java中分隔符之间的文本

java - System.getProperty (“java.class.path” ) 无法在 Web 应用程序中工作

Java 窗口缓冲击键直到用户用鼠标单击

java - Java 和 JS/AS3 之间 URL 解码/编码 UTF-8 的差异(错误!?)

java - 为什么需要 ListModel 对象?