Search code examples
javaswinglayout-managergrid-layoutswingx

JXCollapsiblePane from SwingX in a class is affecting all the other panes created in other objects made by the class


I have a class that creates elements for a grid in a GridLayout, which basically consists of 4 panels that are packed together.

I wanted one of the panels (which contains a JTextArea) to be collapsible because it's fairly verbose and I don't want it to be taking up so much screen space. Naturally, I came across the SwingX library and used the JXCollapsiblePane to do this, and even though it works as intended, it seems as though it keeps affecting all the other JXCollapsiblePanes whenever I click the toggle button on just one of them. It doesn't actually open them, but it makes it so the window expands to accommodate the space as though they were opened. I can take pictures if you want a better description, but later. How do I make it so it doesn't do that? I'm pretty sure I'm not using any static attributes, so I'm not sure why it's doing that.

On a side note, if someone could tell me if this is correct coding style (I feel like what I'm doing is really inefficient with the super-nested panels, new to Swing) that would be nice.

Here are the relevant code snippets from my project:

        JXCollapsiblePane collapsiblePane = new JXCollapsiblePane();
        JButton toggle = new JButton(collapsiblePane.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
        toggle.addActionListener(e -> {
            toggle.setText(collapsiblePane.isCollapsed() ? "▼" : "▶");
        });
        toggle.setText("▶");
        toggle.setPreferredSize(new Dimension(20, 20));
        Border emptyBorder = BorderFactory.createEmptyBorder();
        toggle.setBorder(emptyBorder);
        resultTextPanel.add(toggle);
        collapsiblePane.setCollapsed(true);
        collapsiblePane.setSize(250, 60);
        gridElemPanel.add(resultTextPanel, BorderLayout.NORTH);
         ...
        if (ngramText != null && !ngramText.contains("null")) {
            JTextArea ngramLabel = new JTextArea(ngramText);
            ngramLabel.setLineWrap(true);
            ngramLabel.setWrapStyleWord(true);
            ngramLabel.setFont(new Font("Courier", Font.PLAIN, 12));
            JScrollPane scrollPane = new JScrollPane(ngramLabel);
            scrollPane.setPreferredSize(new Dimension(250, 60));
            scrollPane.getHorizontalScrollBar().setUnitIncrement(16);
            collapsiblePane.add(scrollPane);
            collapsiblePane.setPreferredSize(scrollPane.getPreferredSize());
            gridElemPanel.add(collapsiblePane, BorderLayout.SOUTH);
        }

Solution

  • GridLayout:

    The container is divided into equal-sized rectangles

    so when you change one, all change accordingly.

    If you need more flexibilty (at a price of more complexity) consider GridBagLayout.