本文介紹了如何使JTextArea可滾動(dòng),但仍然設(shè)置了高度?的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有一個(gè)連接到設(shè)備的Java應(yīng)用程序,并在JTextArea
中顯示日志。我希望JTextArea
是可滾動(dòng)的,這是我通過將其放入JScrollPane
中實(shí)現(xiàn)的。包含JTextArea
的JScrollPane
位于BorderLayout
的CENTER
部分。我使用pack()
在JFrame
顯示之前設(shè)置它的大小。但是,這有一些問題:
JTextArea
沒有設(shè)置高度,很薄,文字看不清(第二張圖片里其實(shí)是文字):
使用為JTextArea
設(shè)置的首選大小,它一開始似乎工作得很好。但當(dāng)文本較多時(shí),滾動(dòng)條不會按預(yù)期顯示。它們在縮小JFrame
大小時(shí)出現(xiàn),而不考慮JTextArea
中的文本量。這也不會通過滾動(dòng)顯示所有文本。
另外,設(shè)置最小高度也無濟(jì)于事;它會導(dǎo)致與第一種情況相同的結(jié)果。
我初始化框架的代碼:
JButton connectBtn, disconnectBtn;
JTextArea logArea;
public MyApplication() throws HeadlessException {
super();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new MyWindowListener()); // Disconnect and exit on close
setLayout(new BorderLayout());
connectBtn = new JButton("Connect");
disconnectBtn = new JButton("Disconnect");
disconnectBtn.setEnabled(false);
connectBtn.addActionListener(new ConnectListener()); // Connects to device
disconnectBtn.addActionListener(new DisconnectListener()); // Disconnects from device
logArea = new JTextArea();
logArea.setEditable(false);
// Whatever fixes the problem goes here... e.g.
// logArea.setPreferredSize(new Dimension(100, 200));
JPanel buttons = new JPanel(new BorderLayout());
buttons.add(connectBtn, BorderLayout.LINE_START);
buttons.add(disconnectBtn, BorderLayout.LINE_END);
add(buttons, BorderLayout.PAGE_START);
add(new JScrollPane(logArea), BorderLayout.CENTER);
pack();
setVisible(true);
}
推薦答案
不要玩弄尺寸。
指定文本區(qū)域中所需的行/列,文本區(qū)域?qū)⒂?jì)算其自己的首選大小。
//logArea = new JTextArea();
logArea = new JTextArea(5, 20);
這篇關(guān)于如何使JTextArea可滾動(dòng),但仍然設(shè)置了高度?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,