import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
public class Estudos extends JFrame{
public Estudos(){
super("Exemplo de uma tabela simples");
// colunas da tabela
String[] colunas = {"Nome", "Idade", "Sexo"};
// conteúdo da tabela
Object[][] conteudo = {
{"Osmar J. Silva", "32", "Masculino"},
{"Maria Clara Gomes", "19", "Feminino"}
};
// constrói a tabela
JTable tabela = new JTable(conteudo, colunas);
String[] valores = new String[]{"Masculino", "Feminino"};
TableColumn col = tabela.getColumnModel().getColumn(2);
col.setCellEditor(new MyComboBoxEditor(valores));
// comente se não quiser que o comboxbox apareça quando a
// célula não estiver em modo de edição
col.setCellRenderer(new ComboBoxRenderer(valores));
tabela.setPreferredScrollableViewportSize(new Dimension(350, 50));
Container c = getContentPane();
c.setLayout(new FlowLayout());
JScrollPane scrollPane = new JScrollPane(tabela);
c.add(scrollPane);
setSize(400, 300);
setVisible(true);
}
public static void main(String args[]){
Estudos app = new Estudos();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class ComboBoxRenderer extends JComboBox implements TableCellRenderer {
public ComboBoxRenderer(String[] items){
super(items);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}