简体   繁体   English

JTextArea不断将主面板滚动到顶部

[英]JTextArea keeps scrolling the main panel to the top

I have defined a JTextArea as follows: 我定义了一个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);

Now this component is one of a number of components which has been added to the main JPanel which is defined as follows: 现在,此组件是已添加到主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);

Now the JTextArea component appears near the bottom of the main panel and is partly hidden so you have to scroll down in order to see it all. 现在,JTextArea组件显示在主面板底部附近,并且部分隐藏,因此您必须向下滚动才能看到所有内容。 But the problem I'm getting is that when I click on it, the main panel automatically scrolls back to the top again, hiding most of my JTextArea component again. 但是我遇到的问题是,当我单击它时,主面板会自动再次滚动回到顶部,再次隐藏了我的大部分JTextArea组件。 So after clicking on it, the user has to then scroll down again in order to type something in. 因此,在单击它之后,用户必须再次向下滚动才能键入内容。

But I can't work out why it's doing this. 但是我不知道为什么要这么做。 Is there a problem with using a JTextArea? 使用JTextArea是否有问题? If I use a JTextField then the problem doesn't occur. 如果我使用JTextField,则不会发生此问题。

Any help would be greatly appreciated!! 任何帮助将不胜感激!!

我认为,用scrollPane.getViewport().add(panel) scrollPane.getViewport().setView(panel)替换scrollPane.getViewport().add(panel) scrollPane.getViewport().setView(panel)将解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM