JSlider does not appear in JPanel after being inserted

1

I was trying to add JSlider to JPanel but it does not appear.

Could you tell me where I'm wrong?

import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;

public class Principal extends JFrame{
    public static JPanel pn = new JPanel();
    public static final int VelMin = 0;
    public static final int VelMax = 20;
    public static final int VelInit = 10;

    public static JSlider jsVelocidade= new JSlider(JSlider.HORIZONTAL, VelMin, VelMax, VelInit);

    public static void main(String[] args) {
       new Principal();
    }

    public Principal(){
        super("Semáforo");
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        pn.setPreferredSize(new Dimension(800,500));
        pn.setLayout(null);

        jsVelocidade.setMajorTickSpacing(10);
        jsVelocidade.setMinorTickSpacing(1);
        jsVelocidade.setPaintTicks(true);
        jsVelocidade.setPaintLabels(true);

        pn.add(jsVelocidade);

        add(pn);
        pack();

        setVisible(true);
        setLocationRelativeTo(null);
    }    
}
    
asked by anonymous 08.09.2017 / 19:48

1 answer

2

The problem lies in this line:

pn.setLayout(null);

When you do this, you are removing the layout manager , and without it, you need to set the size and position of each component added in the panel manually. Remove this line as the component appears normally.

More information about Layout Managers can be found in the Guide Oracle official .

And it's always good to mention which screens should be started within the Event-Dispatch-Thread , because swing is not Thread-Safe , and the whole GUI needs to start within this single Thread . This answer explains the reason for this and any issues that may occur. This other answer shows you some ways to start the application within this Thread . p>     

08.09.2017 / 20:10