您好,登錄后才能下訂單哦!
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上
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。