[java] weird behavior when adding a JSplitPane to a JPanel with other components

Started by
0 comments, last by Antheus 18 years ago
Please note that I experienced this problem when I was doing a project for school and I generalized the problem to the below code (otherwise I would have had to post a lot of code).

import javax.swing.*;
import java.awt.*;
 
public class Main {
    
 
    public static void main(String[] args) {
        
        JFrame frame = new JFrame("test");
        JPanel p1 = new JPanel();
        p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
        p1.add(new JButton("Click Me"));
        p1.add(Box.createHorizontalStrut(10));
        p1.add(new JTextField(10));
        
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(p1);  // problem here
        
        JPanel p2 = new JPanel();
        p2.setBackground(Color.blue);
        p2.setPreferredSize(new Dimension(300, 300));
        
        JPanel p3 = new JPanel();
        p3.setBackground(Color.red);
        p3.setPreferredSize(new Dimension(300, 300));
        panel.add(new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, p2, p3));
 
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        
    }
    
}
The GUI undergoes a dramatic and undesirable change in appearence when the line of code

panel.add(p1);  // problem here
is compiled versus when it is commented out. What I want is the JSplitPane to extend the full width of the panel which holds it and have the other JPanel sit above it. However, I cannot get it to do this. When the problem line is commented out, the JSplitPane gives me the behavior I want, but I don't have the other panel. When the panel is in the GUI, the JSplitPane only takes up half the width of the window. Can anyone tell me why the behavior is inconsistent and how I can fix it? Thanks.
Advertisement
Try this:

JPanel panel = new JPanel();panel.setLayout(new BorderLayout());  // <--panel.add(p1, BorderLayout.NORTH);    // <--        ...        JPanel p3 = new JPanel();p3.setBackground(Color.red);p3.setPreferredSize(new Dimension(300, 300));panel.add(new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, p2, p3), BorderLayout.CENTER);            // <--

This topic is closed to new replies.

Advertisement