我正在Java Swing中创建一个JSplitPane。我在拆分窗格中添加PropertyChangeListener
开始拖动分隔线时会调用属性更改方法,但是在拖动后放下分隔线时要调用该方法,这怎么可能?

我正在使用以下代码:

 splitpane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY,
     new PropertyChangeListener() {
      @Override
       public void propertyChange(PropertyChangeEvent pce) {
          JOptionPane.showMessageDialog(null,"Change " +panel.getSize().width);
    }
  });


上面的方法显示了拖动之前面板的宽度,但是我想要拖动之后的宽度。

最佳答案

问题在于,分隔符的位置是在分隔窗格LayoutManager对包含的组件进行布局之前设置的。

该解决方案非常简单,您只需将呼叫包装在SwingUtilities.invokeLater中即可。另一种选择是将ComponentListener添加到拆分窗格中包含的每个组件。

小代码示例:

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.SwingWorker.StateValue;
import javax.swing.UIManager;

public class TestSplitPaneDragging {

    protected void initUI() {
        final JFrame frame = new JFrame();
        frame.setTitle(TestSplitPaneDragging.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setLeftComponent(new JTextArea(24, 48));
        splitPane.setRightComponent(new JTextArea(24, 48));
        splitPane.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        System.err.println(splitPane.getLeftComponent().getWidth());
                    }
                });
            }
        });
        frame.add(splitPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestSplitPaneDragging().initUI();
            }
        });
    }
}

09-12 16:27