我正在尝试让 JTable
与 MouseListener
一起使用。
现在的代码是带有图标的 JTable
的示例程序。
我想要的是,如果您双击一行,则应打开一个对话框
,其中包含整行或仅的信息行中的>索引号
。
但我的问题是命令: table.addMouseListener(this);
不起作用,也许是因为构造函数的原因?
我尝试在 main 方法中使用新对象
,然后创建 MousListener。
public class TableIcon extends JPanel
{
public TableIcon()
{
Icon aboutIcon = new ImageIcon("Mypath");
Icon addIcon = new ImageIcon("Mypath");
Icon copyIcon = new ImageIcon("Mypath");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "Pic1"},
{addIcon, "Pic2"},
{copyIcon, "Pic3"},
};
DefaultTableModel model = new DefaultTableModel(data,columnNames)
{
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
public boolean isCellEditable(int row, int column)
{
return false;
}
};
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize
(table.getPreferredSize());
// ################ MyError #########
table.addMouseListener(this); // Error
// ##################################
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowGUI()
{
TableIcon test = new TableIcon();
JFrame frame = new JFrame("Table Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(test);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
public void mouseClicked(MouseEvent e)
{
System.out.println("clicked");
}
}
在这段代码中,我期望打印带有“clicked”的print
,但我得到的只是这个错误
我的错误
TableIcon 无法转换为 java.awt.event.MouseListener
最佳答案
尝试使用适配器类:
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
//Code for handling the double click event
}
}
});
关于java - 如何让 JTable 上的 MouseListener 正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558729/