如何在 Java 中以编程方式隐藏 JSplitPane 程序的左侧/右侧面板?
JSplitPane 是JComponent 类的子类,它允许我们在水平或垂直方向上将两个组件排列在一个窗格中并排显示。这两个组件的显示区域还可以由用户在运行时进行调整。JSplitPane 的重要方法包括remove()、removeAll()、resetToPreferredSizes() 和 setDividerLocation()。JSplitPane 可以生成 PropertyChangeListener 接口。通过单击左按钮或右按钮,我们可以以编程方式隐藏其中一个窗格(左或右),并且可以为此类按钮生成动作侦听器。
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JSplitPaneHideTest extends JFrame { private JButton leftBtn, rightBtn; private JSplitPane jsp; public JSplitPaneHideTest() { setTitle(" JSplitPaneHide Test"); leftBtn = new JButton("Left Button"); rightBtn = new JButton("Right Button"); jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftBtn, rightBtn); jsp.setResizeWeight(0.5); // Implemention code to hide left pane or right pane ActionListener actionListener = new ActionListener() { private int loc = 0; public void actionPerformed(ActionEvent ae) { JButton source = (JButton)ae.getSource(); if(jsp.getLeftComponent().isVisible() && jsp.getRightComponent().isVisible()) { loc = jsp.getDividerLocation(); jsp.setDividerSize(0); jsp.getLeftComponent().setVisible(source == leftBtn); jsp.getRightComponent().setVisible(source == rightBtn); } else { jsp.getLeftComponent().setVisible(true); jsp.getRightComponent().setVisible(true); jsp.setDividerLocation(loc); jsp.setDividerSize((Integer) UIManager.get("SplitPane.dividerSize")); } } }; rightBtn.addActionListener(actionListener); leftBtn.addActionListener(actionListener); add(jsp, BorderLayout.CENTER); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JSplitPaneHideTest(); } }
输出
广告