如何防止组件 focusability java 摆动

How to prevent component focusability java swing

在我的 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 的值发生变化时,它都会获得焦点并且滚动条 return 到顶部。

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

我尝试了 .setFocusable(false) 方法,但滚动条一直return移动到屏幕顶部。

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

谢谢

移除

infoAreaPane.setVisible(focusHint != null);

如果您不想让某个组件获得焦点,您可以使用:

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

but the scrollbar keep on returning to the top of the screen

不要使用 setText()

您可以尝试直接更新 Document。可能是这样的:

Document doc = textArea.getDocument()
doc.remove(...);
doc.insertString(...);

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

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