JLabel wont change color twice
I have the following code:
public class Test extends JFrame implements ActionListener{
private static final Color TRANSP_WHITE = new Color(new Float(1), new Float(1), new Float(1), new Float(0.5));
private static final Color TRANSP_RED = new Color(new Float(1), new Float(0), new Float(0), new Float(0.1));
private static final Color[] COLORS = new Color[]{ TRANSP_RED, TRANSP_WHITE};
private int index = 0;
private JLabel label;
private JButton button;
public Test(){
super();
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
label = new JLabel("hello world");
label.setOpaque(true);
label.setBackground(TRANSP_WHITE);
getContentPane().add(label);
button = new JButton("Click Me");
button.addActionListener(this);
getContentPane().add(button);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(button)){
label.setBackground(COLORS[index % (COLORS.length - 1)]);
index++;
}
}
public static void main(String[] args) {
new Test();
}
}
When I run it I get the label with the TRANSP_WHITE
backg开发者_StackOverflowround and then when I click the button this color changes to TRANSP_RED
but when I click it again I see no change in color. Does anyone know why?
Thanks
Well, what were you expecting to happen?
label.setBackground(COLORS[index % (COLORS.length - 1)]);
The index variable is hard coded to 0. and COLORS.length -1 is essentially a constant. So every time you click your setting the background to COLORS[0];
If you change your action method to the following you'll get the results you are looking for:
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(button)){
label.setBackground(COLORS[index % COLORS.length]);
index++;
}
}
First: The modulo operator will always return a value between 0 and one less than the value passed to it. So
index % COLORS.length
Will always return a value between 0 and COLORS.length -1.
Second: You were forgetting to increment index after every call.
Hey! You forgot to increment index. In this expression:
label.setBackground(COLORS[index % (COLORS.length - 1)]);
index % (COLORS.length - 1)
is always 0.
BTW. you don't have to use new Float(1)
when creating Color
. 1F
should work too.
Here is the code you have to use
label.setBackground(COLORS[index % (COLORS.length)]);
index++;
You are doing it wrong. It should be done like that
label = new JLabel("hello world"){
public void paintComponent(Graphics g)
{
//draw background
Color old=g.getColor();
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(old);
super.paintComponent(g);
}
};
label.setOpaque(false); // your component is not opaque!
精彩评论