[英]How do I get the MouseListener on a JTable working
我正在嘗試讓JTable
與MouseListener
一起使用。 現在的代碼是帶有圖標的JTable
的示例程序。 我想要的是,如果您雙擊一行,則應打開一個dialog
,其中包含整行的信息或該行的index-number
。 但我的問題是命令: table.addMouseListener(this);
不工作,也許是因為構造函數?
我嘗試在 main 方法中使用new object
,然后創建 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
帶有“clicked”,但我得到的只是這個錯誤My Error TableIcon cannot be cast to java.awt.event.MouseListener
嘗試使用適配器 class:
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
//Code for handling the double click event
}
}
});
您指this
是 class TableIcon
並且它沒有實現接口MouseListener
,但方法addMouseListener()
需要它。
public void addMouseListener(MouseListener l)
如果您想 go 使用TableIcon
class 的方法作為事件處理程序,然后添加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) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.