Creating a JSplitPane with 3 Panels

I would like to create a window with 3 jPanels, split by splitPane-s. The left and right should be changed by the user, and the one in the middle should fill the remaining space.

I created it, but if I move the first splitPane, then the second will move. And I'm not sure if I'm using the best method for what I want.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class MyWindow extends JFrame {

    public MyWindow() {
        this.setLayout(new BorderLayout());

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

        JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
        JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, centerPanel2, rightPanel);

        centerPanel.setLayout(new BorderLayout());
        this.add(sp, BorderLayout.CENTER);
        centerPanel.add(sp2, BorderLayout.CENTER);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(500, 500);
        this.setVisible(true);
    }

}

      

+3


source to share


1 answer


What you are doing looks rather strange to me, adding centerPanel

to the panel with a section and then adding the split panel to centerPane

. Not sure, but I think the latter denies the former.

All you have to do is add the first split panel to the second split panel.



import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;

public class MyWindow extends JFrame {

    public MyWindow() {
        this.setLayout(new BorderLayout());

        JPanel leftPanel = new JPanel();
        leftPanel.setBackground(Color.BLUE);
        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(Color.CYAN);
        JPanel rightPanel = new JPanel();
        rightPanel.setBackground(Color.GREEN);

        JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
        JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

        this.add(sp2, BorderLayout.CENTER);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(500, 500);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new MyWindow();
            }
        });
    }
}

      

+1


source







All Articles