java - 如何让 JTable 上的 MouseListener 正常工作
问题描述
我正在尝试JTable
使用MouseListener
. 现在的代码是一个JTable
带有图标的示例程序。我想要的是,如果你双击一行,一个dialog
应该打开的信息来自整行或只是index-number
来自行的信息。但我的问题是 command:table.addMouseListener(this);
不起作用,也许是因为构造函数?
我尝试new object
在主要方法中使用a,然后创建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");
}
}
在这段代码中,我期望一个print
with"clicked" 但我得到的只是这个错误
My Error
TableIcon cannot be cast to java.awt.event.MouseListener
解决方案
您指的是this
哪个是类TableIcon
,它没有实现接口MouseListener
,但方法addMouseListener()
需要它。
public void addMouseListener(MouseListener l)
如果您也想使用TableIcon
类作为事件处理程序的方法,请为MouseListener
接口添加实现。
public class TableIcon extends JPanel implements MouseListener {
...
public void mouseClicked(MouseEvent e) {
// code for handling of the click event
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
推荐阅读
- mysql - SQL拉取相关人员
- javascript - 使用 Mongoose 和 Typescript,接口的 ref 字段应该使用什么类型?
- migration - 在 Raku 中替代 Perl 的 <>?
- php - PHP中的日期格式 - 找不到解决方案
- javascript - PHP:单击提交后如何返回页面上的同一位置?
- javascript - 根据另一个数组元素过滤多维数组
- java - 通过 PDFBox 将波斯文本写入 pdf
- excel - Excel VBA - 如何组合每行中“n”个单元格的文本?
- c# - WPF 中的 IComparable
- flutter - 跳过在列表中插入数据