【发布时间】:2021-06-25 12:03:46
【问题描述】:
我有一个简单的JTable。 When a row is selected, it is highlighted as expected (see image):
但是当行被取消选择时,行数据消失(见图):
我在运行 JetBrains IntelliJ 随附的 Java 11 JDK 的 Linux 上看到了这一点。
这是一个重现问题的独立示例:
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
public class Main
{
public static void main(String[] args)
{
JTable table = new JTable();
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setModel(new AbstractTableModel()
{
@Override
public String getColumnName(int column)
{
return "Item";
}
@Override
public int getRowCount()
{
return 10;
}
@Override
public int getColumnCount()
{
return 1;
}
@Override
public Object getValueAt(int row, int col)
{
return col == 0 ? "Test string #" + row : "";
}
});
JFrame frame = new JFrame("Test JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(table);
frame.setMinimumSize(new Dimension(250, 200));
frame.pack();
frame.setVisible(true);
}
}
有什么想法吗?
【问题讨论】:
-
我无法使用您的代码重现您的问题,我也没有在代码中看到任何明显的错误
-
如果列不为 0 那么它根据您的三元运算符显示“”是否与它有什么关系?一个 null 或没有选择的列毕竟不是零
-
@experimentunit1998X:我不知道为什么 OP 的
getValueAt(...)的结构是这样的,但是对于当前的表和模型,列不应该是任何东西 but0在方法中。 -
如何取消选择该行?即使在 Windows 上按住 ctrl-click,此项目仍会保留一个边框。在您的屏幕截图中,似乎不存在边框。奇怪
-
在我的测试中,我添加了一个JButton:
JButton clearSelectionBtn = new JButton("Clear Selection"); clearSelectionBtn.addActionListener(e -> { table.clearSelection(); });