Jslider does not appear in Jpanel after inserting

Asked

Viewed 51 times

1

I was trying to add a JSlider in a JPanel but he doesn’t show up.

Could you tell me where I’m going 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);
    }    
}

1 answer

2


The problem is on this line:

pn.setLayout(null);

By doing so, you are removing the layout manager, and without it, you need to set size and position of each component added in the panel manually. Remove that line and the component will appear normally.

More information on Layout Managers can be found in Official Guide to Oracle.

And it is always good to mention that canvases should be started within the Event-Dispatch-Thread, because swing is not Thread-Safe, and the entire GUI needs to start within this single Thread. In this answer it is explained better the reason for this and any problems that may occur. This other answer shows some ways to start the application within this Thread.

  • But there is a way I can use Jslider without taking Pn.setLayout(null)?

  • 1

    @Not Gustavocruz. If you set a layout to null, you are removing it from the component.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.