Flask接口签名sign原理与实例代码浅析
400
2023-01-26
Java如何实现可折叠Panel方法示例
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.addMouseLishttp://tener(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上
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我们的支持。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~