1

我想要一个 jsplitPane 并在运行我的程序时用左组件交换右组件。我将分割位置设置为 0.2 左右。当我交换左组件和右组件并将分割位置设置为 0.8 左右时;jSplitPane 有问题。它被锁定,我无法移动除数。之后也是;当我尝试将另一个组件分配到 JSplitPane 的右侧或左侧时,这些组件会出现 bollixed。在交换左右组件之前,我尝试了 setDivisionLocation() 方法;但它没有效果。还有 repaint() 方法....请指导我

问候...萨贾德

4

1 回答 1

3

我认为您的问题是您两次添加了一个组件(这确实会使想法看起来很奇怪)。例如,您执行以下操作:split.setLeftComponent(split.getRightComponent()).

因此,当您进行交换时,您需要先移除组件:

private static void swap(JSplitPane split) {
    Component r = split.getRightComponent();
    Component l = split.getLeftComponent();

    // remove the components
    split.setLeftComponent(null);
    split.setRightComponent(null);

    // add them swapped
    split.setLeftComponent(r);
    split.setRightComponent(l);
}

演示在这里(也移动了分隔线的位置):

前 后

public static void main(String[] args) {
    JFrame frame = new JFrame("Test");

    final JSplitPane split = new JSplitPane(
            JSplitPane.HORIZONTAL_SPLIT, 
            new JLabel("first"), 
            new JLabel("second"));

    frame.add(split, BorderLayout.CENTER);
    frame.add(new JButton(new AbstractAction("Swap") {
        @Override
        public void actionPerformed(ActionEvent e) {
            // get the state of the devider
            int location = split.getDividerLocation();

            // do the swap
            swap(split);

            // update the devider 
            split.setDividerLocation(split.getWidth() - location 
                    - split.getDividerSize());
        }


    }), BorderLayout.SOUTH);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}
于 2011-02-02T08:00:26.887 回答