JEP
JEP

Reputation: 11

How do i allow my Jslider to fit inside my JPanel?

I am programming a small application and have run into a big bump. I am stuck on why the JSlider won't allow me to add it to the JPanel. When the last line of code reads:

"add.(slider);"

the JSlider covers the entire JPanel. Is this correct and I need to resize my JSlider somehow? Or, have I made a mistake with the code and are not making the Jslider visible within the Jpanel?

Here's my code:

package atmosfile;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JSlider;


import java.awt.*;

public class Main extends JFrame {
private static final long serialVersionUID = 1L;


 public Main() {

     super("Package Choice");
     setSize(800, 600);
     setDefaultCloseOperation(EXIT_ON_CLOSE);
     setLocationRelativeTo(null);

       JPanel panel = new JPanel();

         panel.setLayout(new FlowLayout(1, 100, 500));
         panel.add(new JButton("Package 1"));
         panel.add(new JButton("Package 2"));
         panel.add(new JButton("Package 3"));
         add(panel);

       JSlider slider = new JSlider();   

         slider.setLayout(new FlowLayout(1, 100, 200));
         slider.setMajorTickSpacing(5);
         slider.setPaintTicks(true);
         slider.setSize(200, 200);
         slider.setVisible(true);
         panel.add(slider);


        }    
}

Thanks in advance for any help its most appreciated!

Upvotes: 0

Views: 3281

Answers (1)

Reimeus
Reimeus

Reputation: 159754

The horizontal gap of your FlowLayout is so large that it "pushes" the JSlider component out of the drawable area of the frame. Reducing it brings it back in into view again. Also would recommend avoiding the use of magic numbers (1 = FlowLayout.CENTER):

panel.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 500));

Upvotes: 2

Related Questions