I'm trying to get a JTable
working with a MouseListener
. The code right now is a sample program for a JTable
with Icons. What I want is, that if you double click on a row, a dialog
should open with informations from the whole row or just the index-number
from the row. But my problem is that the command: table.addMouseListener(this);
is not working, maybe is it because of the constructor?
I tried to use a new object
inside the main method and create then the 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");
}
}
In this code I expect a print
with"clicked" but all I get is this error My Error TableIcon cannot be cast to java.awt.event.MouseListener
Try using Adapter class:
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
//Code for handling the double click event
}
}
});
You refer to this
which is class TableIcon
and it does not implement interface MouseListener
, but method addMouseListener()
expects it.
public void addMouseListener(MouseListener l)
If you want to go with approach of TableIcon
class acting as event handler as well, then add implementation for the MouseListener
interface.
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) {
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.