我无法尝试在JTable工作中创建单击行事件。我已将该事件添加到我的JTable中,但是当我运行我的程序并单击该行时,它不会显示该消息。
这是我的代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.SQLException;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class listContacts extends JFrame {
public listContacts(){
setLayout(new FlowLayout());
String[] columnNames = {"GSD Number", "Scheduled Time"};
Object [][] dataTable = {};
DefaultTableModel listTableModel;
listTableModel = new DefaultTableModel(dataTable, columnNames) {
//Prevent user from editing the cells
public boolean isCellEditable(int rowIndex, int mCollIndex){
return false;
}
};
int cont = 1;
while(cont < 10){
listTableModel.addRow(new Object[] {cont, cont + cont} );
cont++;
}
JTable listTable = new JTable(listTableModel);
//This is the code that adds the event to the JTable
listTable.addMouseListener(new MouseAdapter() {
public void rowClicked(MouseEvent e){
JOptionPane.showMessageDialog(null,"You've clicked on this row");
}
});
listTable.setCellEditor(null);
JScrollPane pane = new JScrollPane(listTable);
add(pane);
}
public static void main(String[] args) {
listContacts tester = new listContacts();
tester.setVisible(true);
tester.setDefaultCloseOperation(EXIT_ON_CLOSE);
tester.setSize(800, 200);
tester.setTitle("Just a test");
}
}
有人可以帮忙吗?提前谢谢!
答案 0 :(得分:5)
试试这个......
listTable.addMouseListener(new MouseAdapter() {
// Add this annotation to your method
@Override
public void rowClicked(MouseEvent e){
JOptionPane.showMessageDialog(null,"You've clicked on this row");
}
});
现在编译它......看看它是如何失败的......
rowClicked
不是MouseAdapter
继承的任何接口或类的方法,因此,没有任何东西可以调用它,因为没有人知道......它不在合同范围内鼠标事件通知的要求。
答案 1 :(得分:0)
感谢MadProgrammer,我按照你的建议,将方法的名称更改为mouseClicked并且事件有效。这是我的代码:
listTable.addMouseListener(new MouseAdapter() {
// Add this annotation to your method
@Override
public void mouseClicked(MouseEvent e){
JOptionPane.showMessageDialog(null,"You've clicked on this row");
}
});
再次感谢您的帮助!