[英]JScrollPane doesn't work
我的JScrollPane在JTextArea周圍:
...
errorText = new JTextArea();
errorText.setLineWrap(true);
errorText.setWrapStyleWord(true);
errorText.setPreferredSize(new Dimension(300, 150));
JScrollPane scrollPane = new JScrollPane(errorText);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBorder(BorderFactory.createTitledBorder("Info Area"));
...
和代碼,將文本添加到errorText:
public void setText(String mes) {
e140TEST2.errorText.append(lineNum + ". " + mes + "\n");
lineNum++;
}
添加了幾行后(當文本的高度比JTextArea高時),JScrollPane不起作用(文本不腳)。 可以是什么?
errorText.setPreferredSize(new Dimension(300,150));
不要硬編碼文本區域(或任何組件)的首選大小。 首選大小隨您添加/刪除文本而變化。
而是像這樣創建您的文本區域:
textArea = new JTextArea(5, 30);
提供初始大小。
盡管不是理想的解決方案,但是如果使用JTextPane實例而不是JTextArea實例,則仍可以設置首選的像素大小並保留滾動功能。 另外,JTextPane自動換行,並在單詞邊界處換行(這似乎是您想要的)。 嘗試以下SSCCE:
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
public class PaneWithScroll {
public static void main (String[] args) {
JTextPane errorText = new JTextPane();
//errorText.setLineWrap(true);
//errorText.setWrapStyleWord(true);
errorText.setPreferredSize(new Dimension(300, 150));
JScrollPane scrollPane = new JScrollPane (errorText);
scrollPane.setVerticalScrollBarPolicy
(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBorder (BorderFactory.createTitledBorder("Info Area"));
JFrame frame = new JFrame();
frame.add (scrollPane);
frame.pack();
frame.setVisible (true);
}
}
我應該補充一點,這可能是一個快速補丁。 但是,最佳實踐表明您應始終嘗試將可能依賴於平台的規范與GUI設計脫鈎。 在這種情況下,為絕對尺寸。
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.