简体   繁体   中英

How to have Collapsable/Expandable JPanel in Java Swing

I want a JPanel that can be Collapsed or Expanded when user clicks on a text/icon on its border. I need this type of panel due to space crunch in my application.

I read about CollapsiblePanel class but not sure how to use it.. I think SwingX is needed to be downloaded but did not find that anywhere.

Moreover, it would be better if I get the solution to this in basic Java Swing.

not sure where you looked, but it's not that difficult to find - even given the infrastructure mess we are in ;-)

Go to the project home of SwingX , then follow the link in the first paragraph to the (barebone) download section, down to releases\\1.6.2. Nothing special to the collapsibles themselves, just containers to put components into.

I think you can use a JSplitPane to tackle your problem. Utilizing the property to set the position of divider judiciously, you can achieve what you want.

So here comes a little class purely in Swing :) This implementation assumes the title to be top left...

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class JCollapsiblePanel extends JPanel {
  private TitledBorder border;
  private Dimension visibleSize;
  private boolean collapsible;

  public JCollapsiblePanel(String title, Color titleCol) {
    super();

    collapsible = true;

    border = new TitledBorder(title);
    border.setTitleColor(titleCol);
    border.setBorder(new LineBorder(Color.white));
    setBorder(border);

    // as Titleborder has no access to the Label we fake the size data ;)
    final JLabel l = new JLabel(title);
    Dimension size = l.getPreferredSize();

    addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        if (!collapsible) {
          return;
        }

        Insets i = getBorder().getBorderInsets(JCollapsiblePanel.this);
        if (e.getX() < i.left + size.width && e.getY() < i.bottom + size.height) {
          if (visibleSize == null || getHeight() > size.height) {
            visibleSize = getSize();
          }
          if (getSize().height < visibleSize.height) {
            setMaximumSize(new Dimension(visibleSize.width, 20000));
            setMinimumSize(visibleSize);
          } else {
            setMaximumSize(new Dimension(visibleSize.width, size.height));
          }
          revalidate();
          e.consume();
        }
      }
    });
  }

  public void setCollapsible(boolean collapsible) {
    this.collapsible = collapsible;
  }

  public void setTitle(String title) {
    border.setTitle(title);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM