2

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
manCRO
  • 25
  • 5
  • You should set a new border for your panel with the new title – Sergiy Medvynskyy Apr 26 '16 at 08:23
  • You need a reference to the original instance of `TitledBorder`, then you can use [`TitledBorder#setTitle`](https://docs.oracle.com/javase/8/docs/api/javax/swing/border/TitledBorder.html#setTitle-java.lang.String-) – MadProgrammer Apr 26 '16 at 08:45
  • A really, really horrible way to do it might be to do something like `((JComponent)((JSlider)e.getSource()).getParent()).getBorder()`, but if that doesn't blow up in your face, then you are very, very lucky – MadProgrammer Apr 26 '16 at 08:47

1 Answers1

2

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();
    }
}
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48