我正在使用java RMI和swing,我已经从数据库中读取了值,但是我无法读取此代码中所选行的值。我希望JTable显示所有数据库,它显示服务器中的所有可用数据库,但我无法读取此选定的行值
包schoolclient;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import schoolserver.SchoolInterface;
public class DatabaseList {
JFrame jFrame = null;
JPanel jPanel = null;
JList jList = null;
JTable jTable = null;
String data = null;
schoolserver.SchoolInterface schoolInt = null;
public DatabaseList(SchoolInterface sii) {
schoolInt = sii;
jFrame = new JFrame();
jTable = new JTable(){
public boolean isCellEditable(int row, int column) {
return false;
}
};
jTable.setModel(createTable());
jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable.addMouseListener(new MouseAdapter() {
public void MouseClicked(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e) && (e.getClickCount() == 2)) {
new createListSelection();
}
}
});
JScrollPane scrollPane = new JScrollPane(jTable);
jFrame.add(scrollPane);
jFrame.setSize(200, 200);
jFrame.setVisible(true);
}
private DefaultTableModel createTable() {
DefaultTableModel dtm = new DefaultTableModel();
dtm.addColumn("Databases", createArray());
return dtm;
}
private class createListSelection implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
ListSelectionModel lsm = jTable.getSelectionModel();
data = (String) jTable.getValueAt(jTable.getSelectedRow(), 0);
System.out.println(data);
}
}
}
Object[] createArray() {
ArrayList<Object> al = null;
Object[] x = null;
try {
al = schoolInt.availableDatabases();
x = new Object[al.size()];
int i = 0;
for(Object o : schoolInt.availableDatabases())
x[i++] = o;
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "no connection to database or "
+ "remote server availabe", "Server Information", JOptionPane.OK_OPTION);
}
return x;
}
}
答案 0 :(得分:0)
你看起来过于复杂。不要在侦听器中重新添加侦听器,而只需将一个侦听器,一个MouseListener添加到JTable,然后添加一次。在其中检查双击(按下)并做出响应。类似的东西:
jTable.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
data = (String) jTable.getValueAt(jTable.getSelectedRow(), 0);
System.out.println(data);
}
}
});
其他问题,永远不会调用MouseAdapter中的方法:
jTable.addMouseListener(new MouseAdapter() {
public void MouseClicked(MouseEvent e) {
// ....
}
});
您的大小写错误,并且由于MouseAdapter / MouseListener没有MouseClicked方法(它是mouseClicked
),因此永远不会调用此方法。始终将@Override
注释置于您认为可能为覆盖的任何方法之上,并让编译器警告您是否不是这样。如果你这样做了,你就会得到编译器的警告。
关于你的评论