Search code examples
javajslider

JSlider won't show up unless the window is expanded


Hello im making a game using an MVC layout and cannot get the JSlider to become visible. It's working an fully functional, but will not show unless the window is expanded. Here is my method that creates the JSlider in GameView: `public void startView() {

    playerXPosition = 5; // Initializing the X position
    playerYPosition = 80; // Initializing the Y position
    score = 0;
    tds = 0;
    level = 1;
    lives = 3;

    MyPanel drawingWindow = new MyPanel();
    drawingWindow.setSize(800, 500);
    drawingWindow.setVisible(true);
    this.add(drawingWindow);

    SliderView jSlider = new SliderView();
    jSlider.setSize(this.getWidth() / 4, 50);
    jSlider.setAlignmentX((this.getWidth() / 2) - (this.getWidth() / 2));


    jSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            int tacklerspeed = jSlider.getValue();
            getGameController().updateRatio(tacklerspeed);

            System.out.println("Speed changed ");
            System.out.println(tacklerspeed);

        }
    });

    this.setSize(800, 700);
    this.setVisible(true);
    this.add(jSlider, BorderLayout.NORTH);

    drawingWindow.setFocusable(true);
}`

And here's my SliderView class: `public class SliderView extends JSlider {

public SliderView() {
    this.setEnabled(true);
    this.setPaintTicks(true);
    this.setMaximum(2);
    this.setVisible(true);
    this.setFocusable(false);
    this.setValue(1);
    this.setSnapToTicks(true);



}

}`


Solution

  • You look to be shooting yourself in the foot with your attempts to set sizes of things, but most important, you're calling setVisible(true) on the JFrame before adding the JSlider -- so it remains invisible until the next repaint (resize).

    1. Get rid of all setSize's from your program. Instead let the components size themselves,
    2. or override a getPreferredSize, but in a smart way that allows all components to fully show.
    3. You're adding the slider to its container in the BorderLayout.NORTH position. Be sure that this container is in fact using a BorderLayout.
    4. Be sure to call pack() on your top level window (a JFrame?) before displaying it.
    5. MOST important -- call setVisible(true) on the JFrame after adding all components -- including the JSlider
    6. You're also calling this.getWidth() before rendering your GUI components -- this will return a size of 0 -- test it out to see for yourself.