我正在尝试从读取用户数据库的表中选择一行,并根据我在表中选择的选定行进行更改,然后将字段和组合框更改为表中的选定行。
public class Users extends JFrame implements ActionListener {
JLabel username,password,type,department;
JButton update,delete;
JTextField user_f;JPasswordField password_f;
JComboBox ctype,cdepartment;
JTable user_table;
JScrollPane scroll;
String[] ltype={"ST","TA","PR"};
String[] ldepartment={"CS","IT","IS"};
String Data[][];
String Header[]={"USERNAME","PASSWORD","TYPE","DEPARTMENT"};
ArrayList<domain.user> array=users_db.get_users();
public Users(){
//show_Users();
}
public void show_Users(){
Data=new String[array.size()][4];
for(int i=0;i<array.size();i++){
Data[i][0]=array.get(i).getUsername();
Data[i][1]=array.get(i).getPassword();
Data[i][2]=array.get(i).getType();
Data[i][3]=array.get(i).getDepartment();}
//Defining Table
user_table=new JTable(Data,Header);
scroll=new JScrollPane(user_table);scroll.setBounds(0,0,500,375);
///Windows Components
username=new JLabel("Username");password=new JLabel("Password");
user_f=new JTextField();password_f=new JPasswordField();
update=new JButton("Update");delete=new JButton("Delete");
type=new JLabel("Type");ctype=new JComboBox(ltype);
department=new JLabel("Department");cdepartment=new JComboBox(ldepartment);
username.setBounds(15, 350, 90, 80);user_f.setBounds(15,400,200,30);
password.setBounds(220, 350, 90, 80);password_f.setBounds(220,400,200,30);
type.setBounds(15, 400, 90, 80);ctype.setBounds(15,450,200,30);
department.setBounds(220, 400, 90, 80);cdepartment.setBounds(220,450,200,30);
update.setBounds(120, 520, 90, 30);delete.setBounds(230, 520, 90, 30);
//Adding Actions to button
//update.addActionListener(this);delete.addActionListener(this);
//Creating Object of mouse listener to the table
DefaultTableModel model=(DefaultTableModel)user_table.getModel();
int SRN=user_table.getSelectedRow();
user_f.setText(model.getValueAt(SRN,0).toString());
password_f.setText(model.getValueAt(SRN, 1).toString());
ctype.setSelectedItem(model.getValueAt(SRN, 2).toString());
cdepartment.setSelectedItem(model.getValueAt(SRN, 3).toString());
//End creating
//Adding Components+ Window Settings
add(scroll);
add(username);add(user_f);
add(password);add(password_f);
add(type);add(ctype);add(department);add(cdepartment);
add(update);add(delete);
setSize(500,650);
setLayout(null);
setVisible(true);
}
}
这是框架中的屏幕截图,用于说明问题:
答案 0 :(得分:2)
也许此代码可以提供帮助。您必须像这样在行选择上附加侦听器:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
// do some actions here, for example
// print first column value from selected row
System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
}
});