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

后端 未结 6 1495
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 19:33

I am developing a Java Desktop Application. In it I have 4 JButtons on a JPanel. Now I want that whenever a button is clicked its background color

6条回答
  •  借酒劲吻你
    2021-01-18 20:27

    1. just use null to 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);
      ...
      

提交回复
热议问题