Java如何实现可折叠Panel方法示例
程序员文章站
2024-02-16 23:36:04
1.原理
原理非常简单:就是一个jlabel和jpanel。jlabel显示标题文字以及标明控件当前是处于展开还是折叠状态的图片;而jpanel主要就一个作用——承载控件...
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() { @override public void mouseclicked(mouseevent e) { isexpanded = !isexpanded; panelvisible(); } @override public void mouseentered(mouseevent e) { label.setopaque(true); label.repaint(); } @override public 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上
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。