Java 实现可折叠Panel

作者 : 开心源码 本文共2507个字,预计阅读时间需要7分钟 发布时间: 2022-05-11 共141人阅读

1.原理

????????原理非常简单:就是一个JLabel和JPanel。Jlabel显示标题文字以及标明控件当前是处于开展还是折叠状态的图片;而JPanel主要就一个作使用——承载控件的容器。JLabel通过响应鼠标事件来控制JPanel能否显示。这样即可以达到折叠或者开展的效果。

2.代码

public class JShrinkablePanel extends JPanel {private JLabellabel;private Stringtitle ="";private JPanelcontentPanel =null;private boolean isExpanded =true;private JListlist =new JList();private IconiconExpand =null;private IconiconCollapse =null;public JShrinkablePanel(String title, JPanel contentPanel) {super();this.title = title;this.contentPanel = contentPanel;initComponents();initComponentsStatus();initLayout();initResources();unRegisterEvents();registerEvents();}private void initComponents() {this.label =new JLabel();}private void initComponentsStatus() {this.label.setHorizontalAlignment(JLabel.LEFT);this.label.setVerticalAlignment(JLabel.CENTER);this.label.setVerticalTextPosition(JLabel.CENTER);this.label.setBackground(this.list.getSelectionBackground());this.iconExpand =new ImageIcon("src/Resources/Expand.png");this.iconCollapse =new ImageIcon("src/Resources/Collapse.png");}private void initLayout() {this.setLayout(new GridBagLayout());this.add(this.label,new GridBagConstraints(0,0,1,1,1,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0));this.add(this.contentPanel,new GridBagConstraints(0,1,1,1,1,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0));}private void initResources() {this.label.setIcon(this.iconExpand);this.label.setText(this.title);}private void unRegisterEvents() {this.label.removeMouseListener(this.mouseListener);}private void registerEvents() {this.label.addMouseListener(this.mouseListener);}private MouseListenermouseListener =new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {isExpanded = !isExpanded;panelVisible();}@Overridepublic void mouseEntered(MouseEvent e) {label.setOpaque(true);label.repaint();}@Overridepublic void mouseExited(MouseEvent e) {label.setOpaque(false);label.repaint();}};private void panelVisible() {this.contentPanel.setVisible(this.isExpanded);this.label.setIcon(this.isExpanded ?this.iconExpand :this.iconCollapse);}public static void main(String[] args) {JFrame jf =new JFrame("JShrinkablePanel");jf.setBounds(400,200,400,300);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel panel=new JPanel();panel.add(new JButton("Just for show"));panel.setBorder(BorderFactory.createTitledBorder("Border"));JShrinkablePanel scrollPane=new JShrinkablePanel("TestJShrinkablePanel",panel);jf.add(scrollPane);jf.setVisible(true);}}

3.效果

panel开展鼠标在标题Label上panel开展鼠标没在标题Label上panel折叠鼠标在标题Label上panel折叠鼠标没在标题Label上

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Java 实现可折叠Panel

发表回复