[英]How do I insert a row of data into JTable?
我正在嘗試在 JTable 的第一行插入數據。 固定大小的桌子。 我確實讓它工作了,但如果我要在一個 10 行的桌子上做。 代碼會很尷尬。
我對此很陌生,請暫時不要 lambda。 (如果可能)謝謝。 再見,我需要睡覺。
/**
* A basic 3x3 JTable within JFrame inserting data from top row
*/
public class TestCode extends JTable {
private JTable table;
// Insert at row zero and push other row by one row
public void insertRowZero() {
String one, two, three;
one = "numone";
two = "numtwo";
three = "numthree";
// get row 1 and paste into row 2
table.setValueAt(table.getValueAt(1, 0).toString(), 2, 0);
table.setValueAt(table.getValueAt(1, 1).toString(), 2, 1);
table.setValueAt(table.getValueAt(1, 2).toString(), 2, 2);
// get row 0 and paste into row 1
table.setValueAt(table.getValueAt(0, 0).toString(), 1, 0);
table.setValueAt(table.getValueAt(0, 1).toString(), 1, 1);
table.setValueAt(table.getValueAt(0, 2).toString(), 1, 2);
// not actually insert, but does the job
table.setValueAt(one, 0, 0);
table.setValueAt(two, 0, 1);
table.setValueAt(three, 0, 2);
table.repaint();
}
// Create a fixed size table, 3 row and 3 column
public void createTable() {
String[] columnName = {"x", "y", "z"}; // column row doesn't show ?
Object[][] data = {
{"r0-c0", "r0-c1", "r0-c2"},
{"r1-c0", "r1-c1", "r1-c2"},
{"r2-c0", "r2-c1", "r2-c2"}
};
JFrame frame = new JFrame();
frame.setSize(300, 100);
table = new JTable(data, columnName);
frame.add(table);
frame.setVisible(true);
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestCode.class.getName()).log(Level.SEVERE, null, ex);
}
}
public TestCode() {
// construct
createTable();
insertRowZero();
}
public static void main(String[] args) {
// just a start point
new TestCode();
}
}
好的,我跟着 - camickr 。 很好地解決了謝謝。 信息量很大。 此代碼是預期的。 (幾乎)
/**
* A basic 3x3 JTable within JFrame inserting data from top row
*/
public class TestCode {
private DefaultTableModel tm;
// Insert at row zero and push other row by one row
// and remove row three
public void insertRowZero() {
tm.insertRow(0, new Object[]{"numone", "numtwo", "numthree"});
tm.removeRow(3);
}
// Create a fixed size table, 3 row and 3 column
public void createTable() {
tm = new DefaultTableModel();
JTable table = new JTable(tm);
tm.addColumn("x");
tm.addColumn("y");
tm.addColumn("z");
tm.insertRow(0, new Object[]{"r0-c0", "r0-c1", "r0-c2"});
tm.insertRow(1, new Object[]{"r1-c0", "r1-c1", "r1-c2"});
tm.insertRow(2, new Object[]{"r2-c0", "r2-c1", "r2-c2"});
JFrame frame = new JFrame();
frame.setSize(300, 100);
frame.add(table);
frame.add(new JScrollPane(table)); // needed to show column header
frame.setVisible(true); // don't really want scroll pane
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestCode.class.getName()).log(Level.SEVERE, null, ex);
}
}
public TestCode() {
// construct
createTable();
insertRowZero();
}
public static void main(String[] args) {
// just a start point
new TestCode();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.