我定义了一个 JTextArea 如下:
JTextArea textArea = new JTextArea();
textArea.setText("Some text");
textArea.setEditable(true);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.getVerticalScrollBar().setAutoscrolls(false);
现在这个组件是添加到主 JPanel 中的众多组件之一,定义如下:
JPanel panel = new JPanel();
panel.setName("Some name");
JScrollPane scrollPane = new JScrollPane();
scrollPane.setName("Some name");
scrollPane.getViewport().add(panel);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.getVerticalScrollBar().setAutoscrolls(false);
现在 JTextArea 组件出现在主面板底部附近并且部分隐藏,因此您必须向下滚动才能看到它。但我遇到的问题是,当我单击它时,主面板会自动再次滚动回顶部,再次隐藏我的大部分 JTextArea 组件。所以在点击它之后,用户必须再次向下滚动才能输入内容。
但我不明白为什么要这样做。使用 JTextArea 有问题吗?如果我使用 JTextField 那么问题就不会发生。
任何帮助将不胜感激!!
最佳答案
我认为,将 scrollPane.getViewport().add(panel)
替换为 scrollPane.getViewport().setView(panel)
将解决问题。
关于java - JTextArea 不断将主面板滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15337506/