import javax
import javax
import com
import java
import java
/**
* 測試JTable添加數據
* 在工作中如果遇到頻繁的操作Jtable的數據
* Exception in thread
* 這樣的數組越界的異常
* 供同樣遇到這樣問題的人參考
* @author 蔣家狂潮
* email:
*
*/
public class ThreadTable extends JTable {
private DefaultTableModel model;
static String[] header = new String[] {
public ThreadTable() {
model = new DefaultTableModel(header
this
}
public void deleteRows(int rowCount) throws Exception {
if (rowCount >= model
throw new Exception(
} else {
for (int i = rowCount
model
}
}
}
public void testInsertValue() {
final Vector<String> value = new Vector<String>();
value
value
value
value
Thread thread = new Thread() {
public void run() {
for (int i =
//addValueWithThread(value);//這個方法不會出現越界
addValueWithoutThread(value);//這個方法會出現越界
try {
sleep(
} catch (InterruptedException e) {
// TODO Auto
e
}
}
}
};
thread
}
/**
* 將添加記錄和刪除記錄在一個線程裡走
* @param value
*/
public void addValueWithThread(final Vector value) {
Thread thread = new Thread() {
public void run() {
Runnable runnable = new Runnable() {
public void run() {
model
if (model
try {
deleteRows(
} catch (Exception e) {
// TODO Auto
e
}
}
}
};
SwingUtilities
}
};
thread
}
/**
* 這樣一邊添加記錄
* @param value
*/
public void addValueWithoutThread(final Vector value) {
model
if (model
try {
deleteRows(
} catch (Exception e) {
// TODO Auto
e
}
}
}
public static void main(String[] args) {
try {
UIManager
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto
e
}
JFrame f = new JFrame();
f
ThreadTable table = new ThreadTable();
JScrollPane scroll = new JScrollPane(table);
f
f
f
f
table
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26420.html