How to have Collapsable/Expandable JPanel in Java Swing

后端 未结 3 997
我在风中等你
我在风中等你 2021-02-14 03:45

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

3条回答
  •  隐瞒了意图╮
    2021-02-14 04:21

    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);
      }
    }
    

提交回复
热议问题