表中的Java JComboBox在单击单元格之前未显示 [英] Java JComboBox in table not displaying before cell clicked
问题描述
Ok, so I've got a table setup in which I've added a JComboBox to a specific cell as they've done in the example here, but for some reason the combo box won't display until that cell has been selected. If I select that cell, the combo box opens it's list for me to select from. Whether I change the selection or not, if I click to another cell in the table, it then displays the text of the item selected from the combo box as if it was a simple string displayed in the table as desired.
我的问题是:如何获得它以显示JComboBox中的选定值而不必先选择该单元格?
My question is: How do I get it to display the selected value in the JComboBox without having to select the cell first?
edit:我忘了提到的一件事是;与其像以前那样预先声明DefaultTableModel data
,不如稍后使用model.addRow();
edit: One thing I forgot the mention is; rather than declaring the DefaultTableModel data
before-hand like they have, items are instead added to the DTM later using model.addRow();
推荐答案
You can either try creating your own Renderer as in this example.
public void example(){
TableColumn tmpColum =table.getColumnModel().getColumn(1);
String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
JComboBox comboBox = new JComboBox(DATA);
DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
tmpColum.setCellEditor(defaultCellEditor);
tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
table.repaint();
}
/**
Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
JComboBox combo;
public CheckBoxCellRenderer(JComboBox comboBox) {
this.combo = new JComboBox();
for (int i=0; i<comboBox.getItemCount(); i++){
combo.addItem(comboBox.getItemAt(i));
}
}
public Component getTableCellRendererComponent(JTable jtable,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
combo.setSelectedItem(value);
return combo;
}
}
,或者您可以像此示例中那样自定义默认渲染器.
or you can customize the default Renderer like in this example.
final JComboBox combo = new JComboBox(items);
TableColumn col = table.getColumnModel().getColumn(ITEM_COL);
col.setCellRenderer(new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
label.setIcon(UIManager.getIcon("Table.descendingSortIcon"));
return label;
}
});
第一个示例使该单元格在单击后看起来像JComboBox.第二个示例向JComboCox添加一个箭头图标,以展示JComboBox是可单击的.我使用了第二个示例,结果可以在此处看到.
The first example makes the cell look like the JComboBox after its clicked. The second example adds an arrow icon to the JComboCox that showcases that the JComboBox is clickable. I used the second example, result can be seen here.
这篇关于表中的Java JComboBox在单击单元格之前未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!