所以我一直在尝试检查是否在执行操作之前选择了一行。实现table.getSelectedRow()时,如果没有选择行,则返回-1。但我的默认返回0 下面是一个用于演示该问题的小GUI。它运行良好
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class tester extends JFrame implements ActionListener{
private JTable table;
private int row;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tester window = new tester();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tester() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
// **SETTING OUT MY TABLE OF USERS**
String[] columns1 = new String[] {
"ID", "Name"
};
Object [][] data = {
{"S145","PAPA"},
{"S134","JAKE"},
{"S324","MATTHEW"},
};
DefaultTableModel tm = new DefaultTableModel(data, columns1);
table = new JTable(tm);
table.setBorder(new EmptyBorder(0, 0, 0, 0));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(0, 11, 574, 217);
getContentPane().add(scrollPane);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
row = table.getSelectedRow();
System.out.println("User row is: "+row);
}
});
System.out.println("User row is: "+row);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:2)
不,它不是(返回0
)
在这之间...
private int row;
和此处(initialize
内部而非MouseListener
)...
System.out.println("User row is: "+row);
您永远不会更改row
值,因此它仍然带有默认值,即0
如果您将代码更改为更像......
private void initialize() {
//...
table.addMouseListener(new MouseAdapter() {
//...
});
row = table.getSelectedRow();
System.out.println("User row is: " + row);
}
然后它会打印-1