Hello i am new in using JTable of java, I have a multiple rresult from my database which is stored in resultset. My problem is i am using cellrendered in jtable and i dont have any way but to store resultset in String[][] or Object[][].
String[] columnNames = {"Employee ID", "Firstname","Lastname", "Position"};
String[][] database;//This is where i need to put the result set
DefaultTableModel model = new DefaultTableModel(database,columnNames){
public Class getColumnClass(int column){
return getValueAt(1, column).getClass();
}
};
This is the function to create table
private JComponent createData(DefaultTableModel model)
{
JTable table = new JTable( model )
{
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
if (!isRowSelected(row))
{
c.setBackground(getBackground());
int modelRow = convertRowIndexToModel(row);
String type = (String)getModel().getValueAt(modelRow, 1);
if ("Nick".equals(type)) c.setBackground(Color.GREEN);
if ("Leth".equals(type)) c.setBackground(Color.YELLOW);`
}
return c;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.changeSelection(0, 0, false, false);
table.setAutoCreateRowSorter(true);
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setBounds(252, 11, 404, 402);
return scrollPane;
}
This is where i call function to create table getContentPane().add(createData(model));
and the String[][] database variable is the way to insert data from database.
This is the way that i got in google, so far i dont have any idea in cellrendered thats why i think i need to stored result set in String[][] for me to accomplish my target.
This is where i fetch the data from database
public void loadList(){
String sql = "SELECT emp_id,lname,fname,positional_status from tblEmployee";
try{
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
//what goes here to populate my data fetch from database and put in
// String[][] database?
}
}catch(Exception err){
JOptionPane.showMessageDialog(null, err);
}
}
Any suggestion will be appreciated.