Search code examples
javaswingjpaneljscrollpanejtextarea

JTextArea Doesn't Show Up on JPanel inside JTabbedPane


I have a JTextArea that sits inside a JScrollPane which in turn sits inside a JPanel and that in turn sits inside a Tab of a JTabbedPane.

I know that text gets added to my JTextArea, but when I move between the tabs, the JTextArea is not visible. To read the text, I have to select the text inside the JTextArea, and that then brings up the White colour of the background of the JTextArea. If I don't select, I don't see anything.

I've tried the usual revalidate(); and repaint() but they're not working for me. Here is some of the code in question:

public void writeLogEntry(Alarm alarm)
{


    String value = "Blah Blah Blah";
    logTextArea.append(value);
    SwingUtilities.getWindowAncestor(contentPane).revalidate();
    repaint();
    revalidate();
    setVisible(true);
}

And here is the code for the elements related to the JTextArea:

JPanel logPnl = new JPanel();
logPnl.setLayout(new BorderLayout(10, 10));
JScrollPane logScrollPane = new JScrollPane();
logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logTextArea = new JTextArea("blah blah");
logTextArea.setBounds(10, 10, 550, 300);
logTextArea.setEditable(false);
logScrollPane.add(logTextArea);
logPnl.add(logScrollPane);

contentTabs.addTab("Alarms Log", null, logPnl, "View Log");
contentPane.add(contentTabs);

What am I doing wrong?


Solution

  • You should not be adding components directly to a scrollpane. Instead you add components to the viewport. Or, you specify the component when you create the scrollpane and the component will get added to the viewport for you:

    //JScrollPane logScrollPane = new JScrollPane();
    logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    //logTextArea = new JTextArea("blah blah");
    logTextArea = new JTextArea(5, 40);
    logTextArea.setText("some text");
    //logTextArea.setBounds(10, 10, 550, 300);
    logTextArea.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(logTextArea);