[英]Java - how to make “runnable” JTable?
我在創建JTable時遇到問題,它將每秒顯示一些文本。 我制作MainView,放置JTable,並使用“ TableHandler(JTable table)實現Runnable”類,該類應該向JTable中添加一些時間間隔文本...這是run方法:
public void run() {
for (int i=0; i<5; i++) {
table.setValueAt("text", i, i);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
問題是,在Jtable填充數據之前,MainView不會“顯示”,因此用戶看不到填充:-(
編輯:更多代碼
public MyView(SingleFrameApplication app) {
super(app);
initComponents();
// log of GUI stuff here
TableHandler th = new TableHandler(myTable);
th.createTable(); // just loads data
Timer t = new Timer(100,new ActionListener() {
public void actionPerformed(ActionEvent e) {
th.run();
}
});
t.start();
如果您正在使用Swing並希望按時間間隔執行操作,則應使用一個擺動計時器,如本教程中所述。
將循環轉換為對actionPerformed的調用序列,您將獲得:
new Timer ( 1000, new ActionListener () {
int i = 0; // moved out of loop
@Override
public void actionPerformed ( ActionEvent event ) {
if ( i < 5 ) {
i++;
table.setValueAt ( "text", i, i );
} else {
// stop the timer firing events when the loop end
// condition is reached
( ( Timer ) event.getSource() ).setRepeats ( false );
}
}
} ).start();
您需要從AWT線程進行更新:
public void run() {
for (int i=0; i<5; i++) {
final int x = i;
SwingUtilities.invokeLater( new Runnable() {
public void run() {
table.setValueAt("text", x, x);
}});
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
您所描述的行為最可能的問題是您沒有使用單獨的線程來啟動run方法。 如果直接調用run方法,則在主線程再次可用之前,屏幕不會更新,直到run方法完成后才會出現。
驗證您沒有在代碼中的任何地方調用run(),因為應該在線程中進行處理。
編輯:啟動類的代碼應如下所示:
new Thread(new TableHandler(table)).start();
嘗試在setValueAt()調用之后調用重繪 。 最好包裹在SwingUtilities.invokeLater中 。
如果在線程中運行它,則必須使用SwingUtilities.invokeLater。
這只會將請求排隊到您的繪畫例程中,因此您需要確保通過暫停來調用它們。 它看起來應該像這樣:
in your main--or somewhere equivilent:
new myThread
myThread.start()
myThread.run()
new myRoutine();
while(activelyUpdating)
invokeLater(myRoutine);
sleep(something reasonable, like 1000 for updates every second);
myRoutine
do all your drawing crap
return (do not loop here, that's done in the thread. Just return)
可能有一種方法可以讓您的睡眠等待直到invokeLater隊列為空,但是請確保您也睡眠,因為否則AWT線程(線程“ myRoutine”將在其上運行)將永遠不會有運行的機會,invokeLater線程將無法運行。排隊。
根據您的評論。
呼叫start
不能作為mmyers點run
,使用前者是正確的。
因此應該是:
Thread t = new Thread( this.table ); // or new Thread( this )
t.start(); // call start on the read
並不是
this.table.run();
要么
t.run();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.