我有两个JTextPane,并将它们全部设置为垂直自动滚动,但出于某种原因,我不知道只有一个正在工作。
可能是什么原因?
JTextPane textA = new JTextPane();
textA.setName(text);
textA.setContentType("text/html");
DefaultCaret caret = (DefaultCaret)textA.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane filler = new JScrollPane (textA,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JTextPane textB = new JTextPane();
textB.setName(text + "_T");
textB.setFont(textA.getFont());
DefaultCaret caret_T = (DefaultCaret)textB.getCaret();
caret_T.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane filler_T = new JScrollPane (textB,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(filler); panel.add(filler_T);
filler_T(textB)是唯一正在运作的
答案 0 :(得分:1)
您尚未使用panel
的任何布局。因此JScrollPane filler_T
位于JScrollPane filler
之上,因此JTextPane textA
不可见。
使用布局,例如在代码中添加以下行:
panel.setLayout(new BorderLayout(0, 0));
panel.add(filler,BorderLayout.NORTH);
panel.add(filler_T,BorderLayout.CENTER);
您的窗口将如下所示:
完整运行代码:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
public class TestScroll extends JFrame {
private JPanel panel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestScroll frame = new TestScroll();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestScroll() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout(0, 0));
setContentPane(panel);
JTextPane textA = new JTextPane();
textA.setName("text");
textA.setContentType("text/html");
DefaultCaret caret = (DefaultCaret)textA.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane filler = new JScrollPane (textA,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JTextPane textB = new JTextPane();
textB.setName("text" + "_T");
textB.setFont(textA.getFont());
DefaultCaret caret_T = (DefaultCaret)textB.getCaret();
caret_T.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane filler_T = new JScrollPane (textB,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(filler,BorderLayout.NORTH);
panel.add(filler_T,BorderLayout.CENTER);
pack();
}
}
另外为了更好地理解阅读LayoutManagers