0

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

我正在使用以下代码:

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

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

4

1 回答 1

2

问题是分隔器位置是在拆分窗格布局包含的组件之前设置的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();
            }
        });
    }
}
于 2013-06-12T13:08:46.480 回答