英文:
How to prevent selection of new added element on top of JTable?
问题
我有一个包含一行内容的 JTable。我使用多重选择间隔作为选择模式,此外,执行后的5秒钟内将在表格顶部插入一行新记录。我的问题是:当我运行代码并选择第一行后,经过5秒钟会添加一行新的记录(这没问题),但我得到了两行被选择的情况,而我不希望如此,因为我需要保留旧的选择,这意味着在添加新的记录后,只有第二行被选择。如何在使用多重选择间隔模式时解决这个问题?以下是我的代码:
public static void main(String args[]) {
Object[][] rowData = { { "Hello", "World" }, { "By By", "World" } };
Object[] columnNames = { "A", "B" };
JFrame frame = new JFrame("Selecting JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DefaultTableModel model = new DefaultTableModel(rowData,columnNames);
JTable jtable = new JTable(model);
jtable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane scrollPane1 = new JScrollPane(jtable);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.setSize(640, 300);
frame.setVisible(true);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
model.insertRow(0, rowData[0]);
}
英文:
I have a JTable that contains one row. I'am using multiple selection interval as a selection mode, besides a new row will be inserted on top of the table after 5 seconds from execution. My problem is: When I run the code and select the first row, after 5 seconds a new row is added (this is OK) but I got two selected rows which I do not want because I need to preserve the old selection,that means after adding the new row only the second row is selected. How to resolve this problem using multiple selection interval mode? Here is my code:
public static void main(String args[]) {
Object[][] rowData = { { "Hello", "World" }, { "By By", "World" } };
Object[] columnNames = { "A", "B" };
JFrame frame = new JFrame("Selecting JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DefaultTableModel model = new DefaultTableModel(rowData,columnNames);
JTable jtable = new JTable(model);
jtable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane scrollPane1 = new JScrollPane(jtable);
frame.add(scrollPane1, BorderLayout.CENTER);
frame.setSize(640, 300);
frame.setVisible(true);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
model.insertRow(0, rowData[0]);
}
答案1
得分: 1
你可以在插入行之后立即调用 removeRowSelectionInterval
方法。
类似这样:
int newRowIndex = 0;
model.insertRow(newRowIndex, rowData[0]);
jtable.removeRowSelectionInterval(newRowIndex, newRowIndex);
英文:
You can call removeRowSelectionInterval
method right after you insert the row.
Something like:
int newRowIndex = 0;
model.insertRow(newRowIndex, rowData[0]);
jtable.removeRowSelectionInterval(newRowIndex, newRowIndex);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论