public class LabelResizing2 {
public static JPanel createSliderPanel(
int min, int max, int curr)
{
/*outer panel*/
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createRaisedBevelBorder());
final JLabel valueLabel = new JLabel();
valueLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
/*set up slider*/
final JSlider slider = new JSlider(JSlider.VERTICAL, min, max, curr);
slider.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.add(valueLabel);
panel.add(slider);
/*slider move event*/
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
valueLabel.setText(Integer.toString(slider.getValue()));
}
});
valueLabel.setText(Integer.toString(curr));
return panel;
}
public static void main(String[] args) {
JFrame gui = new JFrame("Label Resizing");
gui.setMinimumSize(new Dimension(500, 500));
gui.add(createSliderPanel(-100, 100, 0));
gui.setVisible(true);
}
}
The problem here is that the slider will move all over the place, as the label resizes from '99' to '100' and from '0' to '-1' etc.
Several questions:
- Why is it bouncing around?
If I put in
valueLabel.setSize(100, 100);
it does absolutely nothing. Why?valueLabel.setMinimumSize(100,100);
will stop it bouncing around, but doesn't actually resize the label. Why?Best solution I've found is to go
slider.setAlignmentX(Component.LEFT_ALIGNMENT);
Is this a good solution?However, this won't work forCENTER_ALIGNMENT
orRIGHT_ALIGNMENT
, what's going on here?If we modify it a bit and put the valueLabel inside a panel.
:
final JPanel labelPanel = new JPanel();
final JLabel valueLabel = new JLabel();
valueLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
labelPanel.add(valueLabel);
labelPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
panel.add(labelPanel);
panel.add(slider);
The slider still moves around, even though the labelPanel isn't resizing (the valueLabel is resizing inside it). What's going on here? Is the layout manager also looking at nested components?