can anyone help me flesh out the problem?
I wanted to insert a combo box into one of the columns of
a JTable. although the combo box is drawn, the list
of the data model fails to render.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableAvecRenderer extends JPanel {
public TableAvecRenderer(){
JTable table = new JTable(new TheModel());
//place table in a scroll pane
JScrollPane pane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setDefaultRenderer(JComboBox.class, new CellRenderer());
this.add(pane);
}
class CellRenderer extends JComboBox
implements TableCellRenderer {
public CellRenderer(){
setOpaque(true);
}
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
//let all the cells in this column
//be rendered as a drop-down list
JComboBox hobbies = (JComboBox)value;
hobbies.setEnabled(true);
return this;
}
}
class TheModel extends AbstractTableModel {
String[] sports = {"Footbals", "BasketBall", "HandBall",
"Hockey"};
JComboBox box = new JComboBox(sports);
Object[] cols = {
"FirstName", "LastName", "Sex",
"Age", "State", "educated", "hobbies"
};
Object[][] rows = {
{"David", "Odimegwu","M", "32",
"Imo", new Boolean(false), box},
{"Micheal", "Eke", "M", "34",
"Abia", new Boolean(true), box},
{"Justina", "Akunnaya", "F", "25",
"Anambra", new Boolean(true), box}
};
//implementing the abstract methods.
public Object getValueAt(int row, int col){
return rows[row][col];
}
public int getColumnCount(){
return cols.length;
}
public int getRowCount(){
return rows.length;
}
//implment this class for renderer
@Override
public Class<?> getColumnClass(int col){
return getValueAt(0,col).getClass();
}
@Override
public String getColumnName(int col){
return (String)cols[col];
}
}
private static void showGUI(){
JFrame frame = new JFrame("Simple Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
TableAvecRenderer contentPane = new TableAvecRenderer();
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
showGUI();
}
});
}
}
thanx