Using a JSlider to change JLabel background
I have set up a JSlider to change the opacity of a JLabel's background. I have found that the only way to make the change take effect, is to toggle the visibility of the JLabel in the stateChanged method. Why is this? Shouldn't just setting the JLabel background to a new color work? Try running this with and without the last couple lines in stateChanged:
package slidertest;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
publicclass Mainextends JFrame{
privatestatic Main instance =new Main();
private JLabel colorLabel =new JLabel(" ");
public Main(){
colorLabel.setOpaque(true);
colorLabel.setBackground(Color.green);
JPanel mainPanel =new JPanel(new BorderLayout());
mainPanel.add(colorLabel, BorderLayout.NORTH);
mainPanel.add(createOpacityColorSlider(colorLabel), BorderLayout.CENTER);
this.add(mainPanel);
}
publicstaticvoid main(String[] args){
instance.setSize(200,200);
instance.setVisible(true);
}
staticfinalint ALPHA_MIN = 0;
staticfinalint ALPHA_MAX = 255;
/**
* @param style
* @param colorLabel
* @return
*/
private JSlider createOpacityColorSlider(final JLabel colorLabel ){
JSlider opacitySlider =new JSlider(SwingConstants.HORIZONTAL,
ALPHA_MIN, ALPHA_MAX, colorLabel.getBackground().getAlpha() );
//Turn on labels at major tick marks.
opacitySlider.setMajorTickSpacing(20);
opacitySlider.setMinorTickSpacing(10);
opacitySlider.addChangeListener(new ChangeListener(){
publicvoid stateChanged(ChangeEvent e){
JSlider source = (JSlider)e.getSource();
int alpha = source.getValue();
Color newColor =new Color(colorLabel.getBackground().getRed(), colorLabel.getBackground().getGreen(), colorLabel.getBackground().getBlue(), alpha);
colorLabel.setBackground(newColor);
//will not work without doing this:
colorLabel.setVisible(false);
colorLabel.setVisible(true);
}
});
return opacitySlider;
}
}
-Eric

