Search code examples
javaswingjlabeljslider

Update JPanel border if JSlider changes


Can somebody tell me in general how I change some attributes of a JPanel/TitledBorder if I change a class variable through a JSlider?

e.g. I have the class variable "number" and change this var through a stateChanged event on the slider. Now I want to achieve that the value of the number is shown within a title border of the panel.

    panelX = new JPanel(new GridLayout(3,0));
    panelX.setBorder(new TitledBorder("P0: X = "));
    frame.add(panelX);

    slider_x = new JSlider(0, 100);
    slider_x.addChangeListener(this);

    panelX.add(slider_x);

@Override
public void stateChanged(ChangeEvent e)
{
    Object source = e.getSource();
    System.out.println(source);
    hasChanged = true;
    if(source instanceof JSlider) {
        update();
    }
}

Is it possible to access the title border of the panel where the event firing slider is attached to?


Solution

  • You can simply set the new border for your panel.

    @Override
    public void stateChanged(ChangeEvent e)
    {
        Object source = e.getSource();
        System.out.println(source);
        hasChanged = true;
        if(source instanceof JSlider) {
            panelX.setBorder(new TitledBorder("P0: X = " + ((JSlider) source).getValue());
            update();
        }
    }