问题
I'm using a JScrollPane to hold a JTextArea for a large area of text. I add the TextArea directly to the JFrame, it works fine. But I add it to the scrollpane and add the scrollpane, I don't see the textarea. Here's my SSCCE:
public class foo extends JFrame{
//gui elements
JTextArea chatMonitor = new JTextArea();
JScrollPane textPane = new JScrollPane();
ChatFrame(final String nickname, final String login, final String server, final String channel){
setSize(500,500);
chatMonitor.setEditable(false);
chatMonitor.setVisible(true);
textPane.add(chatMonitor);
textPane.setAutoscrolls(true);
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textPane.setVisible(true);
add(textPane);
}
}
回答1:
Assuming textPane
is a JScrollPane
, you should never be adding components to it.
Instead use JScrollPane#setViewportView(Component)
JScrollPane
is made of a number components which work together to provide you the functionality required to make the component scrollable...

JScrollPane
has a JViewport
, which is used to contain the component you want to be scrolled. You need to "apply" the component to the view.
Take a closer look at How to use Scroll Panes for more details
来源:https://stackoverflow.com/questions/42527569/components-not-displaying-in-jscrollpane