单击基础滚动窗格时,我需要从表(行和单元格)中完全删除焦点。在单击TableModel中的任何内容之前,不再有任何选择。
请参阅this GIF作为当前问题的示例。
我目前在mousePressed事件监听器中使用的代码:
private void tableScrollPaneMousePressed(MouseEvent e) {
TableUtils.deselectAll(dataTable);
}
// In TableUtils:
/**
* Clear all selections
* @param table
*/
public static void deselectAll(JTable table) {
if (table.isEditing()) {
table.removeEditor();
}
table.clearSelection();
}
修改
这里要求的是可运行的示例。同样的问题:单击表格时会选择一行。单击基础面板时,它会删除所有选择,但桌面上仍然可以使用“焦点”/“光标”。
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTable;
import java.awt.GridBagConstraints;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Dimension;
public class Main {
public static void main(String[] args) {
final JTable table;
JFrame frame = new JFrame();
frame.setSize(new Dimension(600, 450));
frame.setPreferredSize(new Dimension(570, 450));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
frame.getContentPane().add(scrollPane, gbc_scrollPane);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
},
new String[] {
"New column", "New column", "New column", "New column", "New column", "New column"
}
));
scrollPane.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent arg0) {
if (table.isEditing()) {
table.removeEditor();
}
table.clearSelection();
}
});
scrollPane.setViewportView(table);
frame.setVisible(true);
}
}