我为即时交互创建了一个表(用于数独求解器),但鼠标事件(进入、退出、单击)只有在我单击单元格后才会到达单元格渲染器。(对于每个单元格,我必须在激活渲染器之前单击一次。稍后返回该单元格,它将立即工作。)
如何更改我的代码以立即激活表格单元格?或者我可以找出第一次鼠标点击到底发生了什么,这样我就可以在创建表后立即执行这些操作?(我试图在 UI 层次结构的所有级别上捕获鼠标事件,但找不到它。)
我已将表格缩小到最小 1x1 并删除了所有不必要的代码。其余代码如下所示。请注意,鼠标悬停(显示一个黑色小方块)仅在单击后才处于活动状态。(代码完整,可以按原样编译。)
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.EventObject;
public class GUI extends JFrame
{
private class Table extends JTable
{
public Table()
{
super(new AbstractTableModel()
{
public int getRowCount() { return 1; }
public int getColumnCount() { return 1; }
public Object getValueAt(int x, int y) { return null; }
@Override public boolean isCellEditable(int x, int y) { return true; }
});
}
@Override public TableCellRenderer getCellRenderer(int x, int y) { return new Editor(); }
@Override public TableCellEditor getCellEditor(int x, int y) { return new Editor(); }
}
private class Editor extends JComponent implements TableCellEditor, TableCellRenderer, MouseListener
{
private boolean hasFocus = false;
public Editor()
{
addMouseListener(this);
}
@Override public void paintComponent(Graphics g)
{
if (hasFocus)
{
g.fillRect(0, 0, 9, 9);
}
}
public void mouseEntered(MouseEvent e)
{
hasFocus = true;
repaint();
}
public void mouseExited(MouseEvent e)
{
hasFocus = false;
repaint();
}
public void mouseClicked(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public Object getCellEditorValue() { return 0; }
public boolean isCellEditable(EventObject e) { return true; }
public boolean shouldSelectCell(EventObject e) { return false; }
public boolean stopCellEditing() { return true; }
public void cancelCellEditing() { }
public void addCellEditorListener(CellEditorListener l) { }
public void removeCellEditorListener(CellEditorListener l) { }
public Component getTableCellEditorComponent(JTable t, Object v, boolean s, int x, int y) { return this; }
public Component getTableCellRendererComponent(JTable t, Object v, boolean s, boolean f, int x, int y) { return this; }
}
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
setContentPane(new Table());
setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}