[英]Unable to scroll on scrollpane - Java Swing
我有一個Swing應用程序,一旦將其傳遞到GUI,它就會使用字符串更新Textarea的內容。
我的字符串在textarea中實時更新,但是我現在面臨的問題是,在進程仍在運行時,我無法滾動textarea。
任何人都知道這里發生了什么或有解決方案
嘗試1-
public static void appendToJTextArea(String message){
String currentText = GUI.textLogArea.getText();
String newString = message;
String newTextToAppend = currentText + "\n" + newString;
GUI.textLogArea.setText(newTextToAppend);
GUI.frame.update(GUI.frame.getGraphics());
}
嘗試2-
public static void appendToJTextArea(String message){
Runnable runnable = new LogThread(message);
Thread thread = new Thread(runnable);
thread.start();
/**
String currentText = GUI.textLogArea.getText();
String newString = message;
String newTextToAppend = currentText + "\n" + newString;
GUI.textLogArea.setText(newTextToAppend);
GUI.frame.update(GUI.frame.getGraphics());
**/
}
}
class LogThread implements Runnable {
private String test;
public LogThread(String message){
test = message;
}
public void run() {
update(test);
}
private void update(String message) {
System.out.println("BBB"+GUI.textLogArea.getText());
System.out.println("AAA"+message);
String currentText = GUI.textLogArea.getText();
String newString = message;
String newTextToAppend = currentText + "\n" + newString;
GUI.textLogArea.append(newTextToAppend);
}
帶有滾動窗格的GUI類
JPanel panel_1 = new JPanel();
panel_1.setBounds(361, 40, 390, 305);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblScraperLogs = new JLabel("Scraper Logs");
lblScraperLogs.setBounds(0, 0, 390, 31);
lblScraperLogs.setFont(new Font("Cooper Black", Font.PLAIN, 13));
lblScraperLogs.setHorizontalAlignment(SwingConstants.CENTER);
panel_1.add(lblScraperLogs);
textLogArea = new JTextArea();
textLogArea.setEditable(false);
textLogArea.setBounds(10, 23, 380, 282);
JScrollPane scroll = new JScrollPane(textLogArea);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setBounds(10, 23, 380, 282);
panel_1.add(scroll);
但是我現在面臨的問題是當進程仍在運行時,我無法滾動文本區域
聽起來您的長期運行過程正在Event Dispatch Thread (EDT)
。 該線程負責繪制GUI,因此在進程完成執行之前,GUI無法重繪自身。 不要在EDT上運行您的代碼。
而是需要為長時間運行的進程創建一個單獨的Thread
。 也許使用SwingWorker
創建一個單獨的線程,並允許您在數據可用時“發布”數據。 閱讀Swing 並發教程中的這一節,以獲取有關EDT和SwingWorker的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.