[英]Java JComboBox in table not displaying before cell clicked
好的,所以我有一個表設置,其中已按照此處示例中的操作在其中添加了一個JComboBox到特定的單元格,但是由於某種原因,直到選擇了該單元格,組合框才會顯示。 如果我選擇該單元格,則組合框會打開它的列表供我選擇。 無論是否更改選擇,如果單擊表中的另一個單元格,它就會顯示從組合框中選擇的項目的文本,就好像它是根據需要在表中顯示的簡單字符串一樣。
我的問題是:如何獲取它以顯示JComboBox中的選定值而不必先選擇該單元格?
編輯:我忘記提到的一件事是; 與其像以前那樣事先聲明DefaultTableModel data
, model.addRow();
稍后使用model.addRow();
將項目添加到DTM中model.addRow();
這是正常的行為。 表格使用渲染器和編輯器。 單元的默認渲染器只是一個JLabel,因此您看到的只是文本。 當您單擊單元格時,將調用編輯器,因此您會看到組合框。
如果您希望即使不對其進行編輯時該單元格仍看起來像一個組合框,則需要為該列創建一個組合框渲染器。
閱讀Swing教程中有關使用自定義渲染器的部分,以獲取更多信息。
您可以嘗試創建自己的渲染器,如本例所示。
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;
}
}
或者您可以像本示例一樣自定義默認的Renderer。
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是可單擊的。 我使用了第二個示例,結果可以在這里看到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.