Basic example of placing two component on one JPanel container?

20,171

Solution 1

The default Layout manager for JPanel is FlowLayout, so adding components without actually setting the layout to an instance of BorderLayout will produce unexpected results.

To get a half/half layout you could use GridLayout:

JPanel panel= new JPanel(new GridLayout(1, 2));

Solution 2

You must use a different LayoutManager, BorderLayout will not allow you add components that use only 50% of the visible space. I personally use GridBagLayout, which allows you to specify many parameters (free space distribution, new lines of components, alignment, etc.).

Solution 3

You should set the LayoutManager of your JPanel to BorderLayout first (only ContentPanes i.e frame#getContentPane() have a default layout of BorderLayout):

    JPanel panel= new JPanel(new BorderLayout());
    panel.add(scrol2,BorderLayout.WEST);
    panel.add(scrol, BorderLayout.EAST);    
    panel.setBorder(etched);
Share:
20,171
Bernard
Author by

Bernard

Love programming...

Updated on September 19, 2020

Comments

  • Bernard
    Bernard almost 4 years

    Here is my code to add to component (JTextArea and JList) to a panel and put it on the frame. Can I divide half/half by BorderLayout?

    If yes why mine looks messy one stays up one down? What is the other alternative? Regards, Bernard

    import java.awt.*;
    import javax.swing.BorderFactory; 
    import javax.swing.border.Border;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel; 
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    
    
    
    public class SimpleBorder {
    
        public static void main(String[] args) {
    
            JFrame frame = new JFrame();
            frame.setSize(500,500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    
            Border etched = (Border) BorderFactory.createEtchedBorder();
    
    
            String[] items = {"A", "B", "C", "D"};
            JList list = new JList(items);
    
            JTextArea text = new JTextArea(10, 40);
    
            JScrollPane scrol = new JScrollPane(text);
            JScrollPane scrol2 = new JScrollPane(list);
    
            JPanel panel= new JPanel();
            panel.add(scrol2,BorderLayout.WEST);
            panel.add(scrol, BorderLayout.EAST);    
            panel.setBorder(etched);
    
            frame.add(panel);
            frame.setVisible(true);
        }
    
    }