Search code examples
javaswingjscrollpanejtreewindowbuilder

JTree in a JScrollPane with fixed size


I have a JTree inside a JScrollPane which is inside a JPanel.

The problem I got is the width which is not fixed when I fill the JTree with nodes, or with a node with a long name.

Here an example:

enter image description here

As you can see, the left one is longer then the right one.

My goal is to keep them exactly equal in size, splitting the main window at 50% each.

Here the code used to generate the window.

Is there a way to keep the width size of the JScrollPane fixed? Thanks.

public void initialize() {

    this.frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    JMenuBar menuBar = new JMenuBar();
    frame.setJMenuBar(menuBar);

    JMenu mnNewMenu = new JMenu("Services");
    mnNewMenu.setHorizontalAlignment(SwingConstants.CENTER);
    menuBar.add(mnNewMenu);

    frame.getContentPane().setLayout(new MigLayout("", "[grow][grow]", "[grow][grow]"));

    JPanel left_JPanel = new JPanel();
    frame.getContentPane().add(left_JPanel, "cell 0 0,grow");
    left_JPanel.setLayout(new MigLayout("", "[grow]", "[grow]"));

    left_ScrollPane = new JScrollPane();
    left_JPanel.add(left_ScrollPane, "cell 0 0,grow");

    JLabel left_Label = new JLabel("Left Scroll Pane");
    left_Label.setFont(new Font("Tahoma", Font.BOLD, 12));
    left_Label.setForeground(Color.BLUE);
    left_Label.setHorizontalAlignment(SwingConstants.CENTER);
    left_ScrollPane.setColumnHeaderView(left_Label);

    JTree left_tree = new JTree();
    left_ScrollPane.setViewportView(left_tree);

    JPanel right_JPanel = new JPanel();
    frame.getContentPane().add(right_JPanel, "cell 1 0,grow");
    right_JPanel.setLayout(new MigLayout("", "[grow]", "[grow]"));

    JScrollPane right_ScrollPane = new JScrollPane();
    right_JPanel.add(right_ScrollPane, "cell 0 0,grow");

    right_JTree = new JTree(phModel);
    right_JTree.setVisibleRowCount(8);
    right_ScrollPane.setViewportView(right_JTree);

    JLabel right_Label = new JLabel("Right Scroll Pane");
    right_Label.setFont(new Font("Tahoma", Font.BOLD, 12));
    right_Label.setForeground(Color.BLUE);
    right_Label.setHorizontalAlignment(SwingConstants.CENTER);
    right_ScrollPane.setColumnHeaderView(right_Label);
}

Solution

  • My goal is to keep them exactly equal in size, splitting the main window at 50% each.

    Use nested panels with standard layout manager from the JDK.

    The GridLayout makes components the same size.

    Something like:

    JPanel left = new JPanel( new BorderLayout() );
    left.add(leftLabel, BorderLayout.PAGE_START);
    left.add(listScrollPane, BorderLayout.CENTER);
    
    JPanel right = ...
    
    JPanel main = new JPanel( new GridLayout(0, 2) );
    main.add( left );
    main.add( right );
    
    frame.add( main );