1

I want to make a program with a BorderLayout where the center and the east part is graphically separated. I tried the following, but unfortunately the separator is on the left side of the JFrame and not between the centerPanel and the rightPanel.

setLayout(new BorderLayout());

JPanel centerPanel = new JPanel();
JPanel rightPanel = new JPanel();

centerPanel.add(new JLabel("center"));
rightPanel.add(new JLabel("right"));

getContentPane().add(centerPanel, BorderLayout.CENTER);
getContentPane().add(rightPanel, BorderLayout.EAST);

getContentPane().add(new JSeparator(JSeparator.VERTICAL), BorderLayout.LINE_START);

Can someone please help me out?

Exceen
  • 765
  • 1
  • 4
  • 20

1 Answers1

4

You can use a Nested Layout approach to give your center panel a BorderLayout and add the vertical separator to this one instead of the content pane:

JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(new JLabel("center"), BorderLayout.CENTER);
centerPanel.add(new JSeparator(JSeparator.VERTICAL), BorderLayout.LINE_END);

JPanel rightPanel = new JPanel();
rightPanel.add(new JLabel("right"));

getContentPane().add(centerPanel, BorderLayout.CENTER);
getContentPane().add(rightPanel, BorderLayout.LINE_END);

Other notes

1) Since Java 1.4 when using BorderLayout the use of new constants is highly encouraged:

PAGE_START
PAGE_END
LINE_START
LINE_END
CENTER

From How to Use BorderLayout tutorial (bold text mine):

Before JDK release 1.4, the preferred names for the various areas were different, ranging from points of the compass (for example, BorderLayout.NORTH for the top area) to wordier versions of the constants we use in our examples. The constants our examples use are preferred because they are standard and enable programs to adjust to languages that have different orientations.

2) Please avoid extending Swing components if you won't add any Swing related feature. See:

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69