Search code examples
javaswingjslider

changeListener not working for JSlider


How to print the JLabel at the top?

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SampleFrame extends JFrame {

    private JPanel contentPane;
    private JPanel q;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SampleFrame frame = new SampleFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public SampleFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        JPanel p = new JPanel();
        q = new JPanel();

        JSlider pine = new JSlider();
        contentPane.add(p, BorderLayout.CENTER);
        p.add(pine);

        contentPane.add(q, BorderLayout.NORTH);
        pine.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent arg0) {
                JSlider sl = (JSlider)arg0.getSource();
                String a = ((Integer)sl.getValue()).toString();
                q.add(new JLabel(a));
            }
        });
    }

}

Solution

  • How to print the JLabel at the top?

    Create the JLabel and add it to the GUI when you initially create the GUI and make the JLabel an instance variable. So instead of adding a JPanel to the NORTH, you just add the label to the NORTH.

    Then when the ChangeListener fires you just use label.setText(...) to change the value of the label.

    You don't want to create a new label every time because then you need to revalidate() and repaint the panel to make sure the layout manager is invoked.