Swing中的JSplitPane propertyChange事件

时间:2013-06-12 12:49:50

标签: java swing jsplitpane propertychangelistener

我在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);
    }
  });

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

1 个答案:

答案 0 :(得分:2)

问题是在分割窗格LayoutManager布置所包含的组件之前设置了分隔符位置。

解决方案非常简单,您只需将呼叫包裹在SwingUtilities.invokeLater即可。另一种方法是将ComponentListener添加到splitpane中包含的每个组件。

代码的小例子:

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();
            }
        });
    }
}