简体   繁体   中英

JTextArea keeps scrolling the main panel to the top

I have defined a JTextArea as follows:

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 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. 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. 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? If I use a JTextField then the problem doesn't occur.

Any help would be greatly appreciated!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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