我正在製作一個用於添加學生和教師數據的程序。我想,以示對學生或教師上表中的數據通過選擇單選按鈕如何使單選按鈕更改表格數據
public void paneling(){
panell = new JPanel(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(); //make the table
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
panell.add(scroll,BorderLayout.CENTER);
panel4 = new JPanel();
panel4.setLayout(new FlowLayout());
rb_siswa = new JRadioButton("Siswa");
rb_dosen = new JRadioButton("Dosen");
ButtonGroup bg = new ButtonGroup();
bg.add(rb_siswa);
bg.add(rb_dosen);
rb_siswa.setSelected(true); //i set RadioButton siswa default
panel4.add(rb_siswa);
panel4.add(rb_dosen);
panell.add(panel4,BorderLayout.NORTH);
if(rb_siswa.isSelected()){ //the first if
String[] columnNames= {"NIM", "ID_Jurusan", "ID_Kelas", "Name", "Tanggal_Lahir", "Gender", "Semester", "Alamat", "email", "nohp"};
model.setColumnIdentifiers(columnNames);
try{
sql = "select * from siswa";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
NIM = rs.getString("NIM");
IDJurusan = rs.getString("id_jurusan");
IDKelas = rs.getString("id_kelas");
Name = rs.getString("Nama");
TL = rs.getString("TanggalLahir");
gender = rs.getString("JenisKelamin");
Semester = rs.getString("Semester");
alamat = rs.getString("Alamat");
email = rs.getString("e-mail");
nohp = rs.getString("nohp");
model.addRow(new Object[]{NIM, IDJurusan, IDKelas, Name, TL, gender, Semester, alamat, email, nohp});
}
}catch(Exception aae){
JOptionPane.showMessageDialog(null, aae.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if(rb_dosen.isSelected()){ // the second if
String[] columnNames= {"ID_Dosen", "Name", "Gender", "Alamat", "email", "nohp"};
model.setColumnIdentifiers(columnNames);
try{
sql = "select * from siswa";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
IDDosen = rs.getString("IDDosen");
Name = rs.getString("Nama");
gender = rs.getString("JenisKelamin");
alamat = rs.getString("Alamat");
email = rs.getString("email");
nohp = rs.getString("nohp");
model.addRow(new Object[]{IDDosen, Name, gender, alamat, email, nohp});
}
}catch(Exception aae){
}
}
我想打,如果我選擇單選按鈕表變化。我需要做一個按鈕?
this is how the table looks like, hope can help you imagine
你有沒有試過'table.revalidate()'或'table.repaint()'進行更改的'模型後JTable'。請記住,更改相同的模型對象並不保證視圖值的更改。相反,在使用它之前創建一個新的'DefaultTableModel'對象或將其設爲空。此鏈接可能對您有所幫助。 http://stackoverflow.com/a/30117380/1540330 –
@VighaneshGursale已經和它不工作 –