我已经编写了这部分代码来获取用户单击两次的行索引,但是每行返回-1。请解决问题。
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class A extends MouseAdapter {
JFrame frame = new JFrame();
Object data[][] = {{"1","Jahanzeb"},{"2","Ahmed"},{"3","Shaikh"}};
String col[] = {"#","Names"};
JTable table = new JTable(data,col);
JScrollPane scroll = new JScrollPane(table);
public static void main(String arg[]) {
new A();
}
public A() {
table.addMouseListener(this);
table.setEnabled(false); // because table should not be editable
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.add(table);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2)
System.out.println(table.getSelectedRow());
}
}
答案 0 :(得分:1)
如果未启用表格,则无法选择任何行。
认为您需要实现自己的表模型并将editable设置为false。
DefaultTableModel tableModel = new DefaultTableModel(data, col)
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table.setModel(tableModel);
答案 1 :(得分:0)
对我来说,这段代码运行正常。
public class A extends MouseAdapter {
JFrame frame = new JFrame();
Object data[][] = { { "1", "Jahanzeb" }, { "2", "Ahmed" },
{ "3", "Shaikh" } };
String col[] = { "#", "Names" };
JTable table = new JTable(data, col);
JScrollPane scroll = new JScrollPane(table);
public static void main(String arg[]) {
new A();
}
public A() {
table.addMouseListener(this);
DefaultTableModel tableModel = new DefaultTableModel(data, col) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table.setModel(tableModel);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scroll);
frame.add(table);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2)
System.out.println(table.getSelectedRow());
}
}
答案 2 :(得分:0)
您也可以在不依赖selectedRow的情况下获取单击的行并使用mousevent。
public void mouseClicked(MouseEvent e) {
JTable table = (JTable) e.getSource();
int row = table.rowAtPoint(e.getPoint());
int column = table.columnAtPoint(e.getPoint());
}