J86*_*J86 1 java swing jpanel jscrollpane jtextarea
我有一个JTextArea,它位于一个JScrollPane中,而JScrollPane又位于一个JPanel内,而后者又位于JTabbedPane的Tab内.
我知道文本会添加到我的JTextArea中,但是当我在选项卡之间移动时,JTextArea不可见.要阅读文本,我必须选择JTextArea中的文本,然后调出JTextArea背景的白色.如果我不选择,我什么都看不到.
我已经尝试了平常revalidate();
,repaint()
但他们不适合我.以下是一些有问题的代码:
public void writeLogEntry(Alarm alarm)
{
String value = "Blah Blah Blah";
logTextArea.append(value);
SwingUtilities.getWindowAncestor(contentPane).revalidate();
repaint();
revalidate();
setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)
以下是与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);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您不应该将组件直接添加到滚动窗格.而是将组件添加到视口.或者,在创建滚动窗格时指定组件,组件将添加到视口中:
//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);
Run Code Online (Sandbox Code Playgroud)