3

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

}
Bernard
  • 4,240
  • 18
  • 55
  • 88

3 Answers3

5

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));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
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.).

Laf
  • 7,965
  • 4
  • 37
  • 52
2

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);
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138