Search code examples
javaswingjtablejscrollpane

Resizing JPanel containing a JscrollPane having a JTable


enter image description here

I have a JPanel(named mainJP) which has a few buttons and labels (uses BorderLayout). Next it adds another JPanel (named JP1) and inside it a ScrollPane with a JTable. I want to be able to resize JP2 and in turn all its child components (ScrollPane and JTable). So that I can see few more rows of the JTable without having to scroll. Also inorder to resize JP1, other siblings of JP1 should adjust themselves. Not sure how to achieve that.

As the image shows I already have a few features implemented - to entirely delete JP1, to expand/collapse JP1 view, to delete and add rows in the JTable.

So basically I want to be able to drag the mouse at bottom border of JP1 to vertically increase the size of JP1 and its child components (ScrollPane and JTable).

As described in a few of the below solutions, I am still confused at which level should I incorporate a JSpiltPane - as it allows only adding 2 components. I think all the JP1 should be in the JSplitPane. However there can be more than one JP1 components and they are dynamically added.


Solution

  • To add extra components to the JSplitPane is easy. Put a JPanel in each pane you want to show your components, then add the components to this panel -- you can customize the layout as needed.

    Something like this will put a JSplitPane in an already create JFrame, add a JPanel to each Pane, and then add some JLabels to the left side, a JTextField to the right. The splitpane will expand to the size of the JFrame it's in.

    JSplitPane splitPane = new JSplitPane();
    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();
    JLabel label1 = new JLabel();
    JLabel label2 = new JLabel();
    JTextField textField = new JTextField();
    GridBagConstraints gBC = new GridBagConstraints();
    
    getContentPane().setLayout(new GridBagLayout());
    leftPanel.setLayout(new GridBagLayout());
    rightPanel.setLayout(new GridBagLayout());
    
    // I'm not going to bother doing any layout of the label or textfield here
    leftPanel.add(label1, new GridBagConstraints());
    leftPanel.add(label2, new GridBagConstraints());
    rightPanel.add(textField, new GridBagConstraints());
    
    splitPane.setLeftComponent(leftPanel);
    splitPane.setRightComponent(rightPanel);
    
    gBC.fill = GridBagConstraints.BOTH;
    gBC.weightx = 1.0;
    gBC.weighty = 1.0;
    getContentPane().add(splitPane, gBC);
    
    pack();