嗨,如果你把JComboBox JTable和String []數組到JComboBox一切正常。如果您將自己的數據類型添加到JComboBox,則在同一列中選擇值會變得很複雜。這裏是official example。嘗試改變以下部分:JTable,JComboBox使用自定義對象
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
分爲:
JComboBox comboBox = new JComboBox();
comboBox.addItem(new Test("Snowboarding"));
comboBox.addItem(new Test("Rowing"));
comboBox.addItem(new Test("Knitting"));
comboBox.addItem(new Test("Speed reading"));
comboBox.addItem(new Test("Pool"));
comboBox.addItem(new Test("None of the above"));
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
,並創造新的數據類型:
public class Test {
private String name;
public Test(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
你會看到,當你在女巫點擊表格單元格存在的JComboBox與自定義數據類型。第一列單元格的值被自動選擇。如何解決這個問題?
編輯1:我加了SSCCE。
主類:
import java.awt.BorderLayout;
public class windw extends JFrame {
private JPanel contentPane;
private JTable table;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
windw frame = new windw();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public windw() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
table = new JTable();
String[] grupes2 = new String[3];
grupes2[0] = "first";
grupes2[1] = "second";
grupes2[2] = "third";
table.setModel(new DefaultTableModel(
new Object[][] {
{new JComboBox<String>(grupes2)},
{new JComboBox<String>(grupes2)},
{new JComboBox<String>(grupes2)},
{new JComboBox<String>(grupes2)},
{new JComboBox<String>(grupes2)},
{new JComboBox<String>(grupes2)},
{new JComboBox<String>(grupes2)},
},
new String[] {
"Column name"
}
));
TableColumn sportColumn = table.getColumnModel().getColumn(0);
sportColumn.setCellEditor(new DefaultCellEditor(new JComboBox<String>(grupes2)));
sportColumn.setCellRenderer(new Renderer(grupes2));
contentPane.add(table, BorderLayout.CENTER);
}
}
渲染:
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class Renderer extends JComboBox implements TableCellRenderer {
public Renderer(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());
}
// Select the current value
setSelectedItem(value);
return this;
}
}
爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2012-01-10 14:37:58