2016-11-25 100 views
1

我无法将JButton的默认颜色设置为黄色?如何设置JButton的默认背景颜色?

同样,一旦按钮被点击,它应该变成红色,如果它已经是红色,它可以点击变回黄色。我应该做什么的任何想法?

private void goldSeat1ActionPerformed(java.awt.event.ActionEvent evt){           

    // TODO add your handling code here: 

    goldSeat1.setBackground(Color.YELLOW); 

}           

private void goldSeat1MouseClicked(java.awt.event.MouseEvent evt) {          

    // TODO add your handling code here: 

    goldSeat1.setBackground(Color.red); 

} 
+0

您是否曾尝试首先使用** ActionPerformed **方法(默认情况下)?在进行任何更改之前,每次检查带有**按钮的颜色获取器**的颜色? –

+0

我不确定为什么你需要一个鼠标监听器,只需要为你的JButton使用Action监听器。 – KyleKW

+2

为了更好的帮助,请尽快发布[mcve] – Frakcool

回答

1

enter image description here

要设置一个JButton的背景色,你可以使用setBackground(Color)

如果你想切换按钮,你必须添加一个ActionListener到按钮,所以当它被点击时,它会改变。你不要必须使用MouseListener

我在这里所做的是我设置了一个布尔值,每次点击按钮时都会自行翻转。 (TRUE变为FALSE,点击时FALSE变为TRUE)。 XOR已被用来实现这一点。

既然你想要比原来的JButton更多的属性,你可以通过从JButton扩展它来定制你自己的属性。

这样做可让您享受JComponents的好处,同时允许您添加自己的功能。我的定制按钮

实施例:

class ToggleButton extends JButton{ 

    private Color onColor; 
    private Color offColor; 
    private boolean isOff; 

    public ToggleButton(String text){ 
     super(text); 
     init(); 
     updateButtonColor(); 
    } 

    public void toggle(){ 
     isOff ^= true; 
     updateButtonColor();    
    } 

    private void init(){ 
     onColor = Color.YELLOW; 
     offColor = Color.RED; 
     isOff = true; 
     setFont(new Font("Arial", Font.PLAIN, 40));  
    } 

    private void updateButtonColor(){ 
     if(isOff){ 
      setBackground(offColor); 
      setText("OFF"); 
     }   
     else{ 
      setBackground(onColor); 
      setText("ON"); 
     }   
    } 
} 

的JPanel的实施例为包含定制按钮:

class DrawingSpace extends JPanel{ 

    private ToggleButton btn; 

    public DrawingSpace(){ 
     setLayout(new BorderLayout()); 
     setPreferredSize(new Dimension(200, 200)); 
     btn = new ToggleButton("Toggle Button"); 
     setComponents(); 
    } 

    private void setComponents(){ 
     add(btn); 
     btn.addActionListener(new ActionListener(){    
      @Override 
      public void actionPerformed(ActionEvent e){ 
       btn.toggle(); //change button ON/OFF status every time it is clicked 
      } 
     }); 
    } 
} 

浇道类驱动代码:

class ButtonToggleRunner{ 
    public static void main(String[] args){ 

     SwingUtilities.invokeLater(new Runnable(){   
      @Override 
      public void run(){  
       JFrame f = new JFrame("Toggle Colors"); 
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       f.add(new DrawingSpace()); 
       f.pack(); 
       f.setLocationRelativeTo(null); 
       f.setVisible(true);    
      } 
     });    
    } 
} 
+0

如果我使用GUI Swing创建了JButton,这会更困难吗? – Smiddy