0

在我的 java swing 应用程序中,每当我单击表单的字段时,我想显示一个信息文本(屏幕顶部的 JTextArea)。为此,我实现了接口 PropertyChangeListener 如下:

private final class FocusChangeHandler implements PropertyChangeListener {
    @Override
    public void propertyChange(final PropertyChangeEvent evt) {
        final String propertyName = evt.getPropertyName();
        if (!"permanentFocusOwner".equals(propertyName)) {
            return;
        }

        final Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

        final String focusHint = (focusOwner instanceof JComponent) ? ((String) ValidationComponentUtils.getInputHint((JComponent) focusOwner))
                : null;

        infoArea.setText(focusHint);
        infoAreaPane.setVisible(focusHint != null);
    }
}

我的问题是,每当 infoArea 的值发生变化时,它都会获得焦点并且滚动条返回顶部。

我想防止这种行为,我想更新 infoArea 的值而不关注它。

我尝试了 .setFocusable(false) 方法,但滚动条继续返回屏幕顶部。

如果需要任何进一步的信息,请告诉我。

谢谢

4

3 回答 3

0

消除

infoAreaPane.setVisible(focusHint != null);
于 2015-01-12T15:14:42.787 回答
0

如果您不希望组件获得焦点,您可以使用:

JTextArea textArea = new JTextArea(...);
textArea.setFocusable( false );

但滚动条继续返回屏幕顶部

不要使用setText().

相反,您可以尝试Document直接更新。也许是这样的:

Document doc = textArea.getDocument()
doc.remove(...);
doc.insertString(...);
于 2015-01-12T15:36:30.147 回答
0

我找到了解决这个问题的方法。

private final class FocusChangeHandler implements PropertyChangeListener {
    @Override
    public void propertyChange(final PropertyChangeEvent evt) {
        final String propertyName = evt.getPropertyName();
        if (!"permanentFocusOwner".equals(propertyName)) {
            return;
        }

        final Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

        final String focusHint = (focusOwner instanceof JComponent) ? ((String) ValidationComponentUtils.getInputHint((JComponent) focusOwner))
                : null;
        final int scrollBarPosition = panelScrollPane.getVerticalScrollBar().getValue();
        infoAreaPane.setVisible(focusHint != null);
        infoArea.setText(infoHint);
        if(focusHint != null) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() { 
                       panelScrollPane.getVerticalScrollBar().setValue(scrollBarPosition);
                   }
                });
        }
    }
}
于 2015-01-12T16:25:10.350 回答