JSplitPane:有没有办法显示/隐藏其中一个窗格?

Jas*_*n S 6 java swing jsplitpane

我有一个带有两个组件A和B的JSplitPane,但有时我希望能够隐藏B,以便满足以下任一条件:

  • 组件A和B在JSplitPane中可见
  • 只有组件A在JSplitPane占用的空间中可见

有没有办法做到这一点?

Hov*_*els 5

哎呀,我会尝试一个解决方案......

import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;

public class Test {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      final JPanel contentPane = (JPanel)frame.getContentPane();

      final JButton leftBtn = new JButton("Left Button");
      final JButton rightBtn = new JButton("Right Button");
      final JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
            leftBtn, rightBtn);
      ActionListener actionListener = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JButton source = (JButton)e.getSource();
            if (jsp.isVisible()) {
               jsp.remove(rightBtn);
               jsp.remove(leftBtn);
               jsp.setVisible(false);
               contentPane.removeAll();
               contentPane.add(source);
            } else {
               contentPane.removeAll();
               jsp.setLeftComponent(leftBtn);
               jsp.setRightComponent(rightBtn);
               jsp.setDividerLocation(0.5);
               jsp.setVisible(true);
               contentPane.add(jsp);
            }
            contentPane.revalidate();
            contentPane.repaint();
            source.requestFocusInWindow();
         }
      };
      rightBtn.addActionListener(actionListener);
      leftBtn.addActionListener(actionListener);
      contentPane.add(jsp);
      contentPane.setPreferredSize(new Dimension(800, 600));
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      jsp.setDividerLocation(0.5);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}
Run Code Online (Sandbox Code Playgroud)


use*_*421 1

如果您引用了组件 A 和 B ,您可以使用组件 A 或 B 的JSplitPane.remove()方法JComponent.setVisible(false)方法。

测试代码:

    final JFrame f = new JFrame();
    final JSplitPane jsp = new JSplitPane();
    final JButton leftB = new JButton("Left: Hide Self");
    final JButton rightB = new JButton("Right: Show Left");
    jsp.setOneTouchExpandable(true);
    leftB.addActionListener(new ActionListener() {
        @Override public void actionPerformed(ActionEvent e) {
            jsp.remove(leftB);
        }
    });
    rightB.addActionListener(new ActionListener() {
        @Override public void actionPerformed(ActionEvent e) {
            jsp.setLeftComponent(leftB);
        }
    });
    jsp.setLeftComponent(leftB);
    jsp.setRightComponent(rightB);
    f.add(jsp);
    f.setSize(800, 600);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Run Code Online (Sandbox Code Playgroud)