Steve Steve - 1 year ago 65
Java Question

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);

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

jSlider.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent e) {
int tacklerspeed = jSlider.getValue();

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


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


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

public SliderView() {



Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download