Search code examples
javaswinglayout-managerborder-layout

BorderLayout - only one of two components appears in SOUTH


I am trying to display 2 sliders in the bottom but it displays only the second slider and not the first. How can I correct it?

package applets;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TheFrame extends JFrame{
private JSlider slider1,slider2;
private DrawOval myPanel;
TheFrame(){
    super("The Oval");
    myPanel = new DrawOval();
    myPanel.setBackground(Color.RED);
    slider1 = new JSlider(SwingConstants.HORIZONTAL,0,200,10);
    slider2 = new JSlider(SwingConstants.HORIZONTAL,0,120,6);
    slider1.setMajorTickSpacing(10);
    slider1.setPaintTicks(true);
    slider1.setPaintLabels(true);
    slider2.setLabelTable(slider1.createStandardLabels(10));
    slider2.setMajorTickSpacing(6);
    slider2.setPaintTicks(true);
    slider2.setPaintLabels(true);
    slider2.setLabelTable(slider2.createStandardLabels(6));
    slider1.addChangeListener(
            new ChangeListener(){
                public void stateChanged(ChangeEvent e){
                    myPanel.SetD1(slider1.getValue());
                }
            }
            );  
    slider2.addChangeListener(
            new ChangeListener(){
                public void stateChanged(ChangeEvent e){
                    myPanel.SetD2(slider2.getValue());
                }
            }
            ); 
    add(slider1,BorderLayout.SOUTH);
    add(slider2,BorderLayout.SOUTH);
    add(myPanel,BorderLayout.CENTER);
}
}

Solution

  • You are trying to display the sliders on top of each other; try adding the first one to BorderLayout.NORTH or another location instead. If you want to display them both next to each other at the south, you could use

    JPanel panel = new JPanel(new GridLayout(2, 1));
    panel.add(slider1);
    panel.add(slider2);
    add(panel);
    

    or another container.