我有一个列出从 SQL 查询返回的客户信息的 JTable。如何设置表格,以便用户可以通过双击或勾选复选框来选择一行,然后用所选客户名称填写 JTextField?
问问题
452 次
2 回答
3
这里有一个示例代码去 fwd
public class PersonTable {
JTable table;
public PersonTable() {
final MyTableModel myTableModel = new MyTableModel();
myTableModel.fill();
table = new JTable(myTableModel);
JFrame frame = new JFrame("Persons");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
final JTextField t1 = new JTextField(10);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int selectedRow = table.getSelectedRow();
Object valueAt = myTableModel.getValueAt(selectedRow, 0);
t1.setText((String) valueAt);
}
});
panel1.add(new JLabel("Name"), BorderLayout.EAST);
panel1.add(t1, BorderLayout.WEST);
panel.add(new JScrollPane(table), BorderLayout.NORTH);
panel.add(panel1, BorderLayout.SOUTH);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public class MyTableModel extends AbstractTableModel {
String[] columnName = new String[]{"Customer Name", "Phone Number", "Area"};
String[][] valueA = null;
public void fill() {
valueA = new String[3][columnName.length];
for (int i = 0; i < 3; i++) {
valueA[i][0] = "Name" + i;
valueA[i][1] = "989481125" + i;
valueA[i][2] = "Area No" + i;
}
}
@Override
public int getRowCount() {
return valueA.length;
}
@Override
public String getColumnName(int column) {
return columnName[column];
}
@Override
public int getColumnCount() {
return columnName.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return valueA[rowIndex][columnIndex];
}
}
public static void main(String[] args) {
new PersonTable();
}
}
于 2012-12-02T17:51:15.897 回答
1
尝试阅读有关如何使用 JTables 的 Java Swing 教程。基本上,您为行选择编写了一个侦听器:
于 2012-12-02T17:25:26.010 回答