在表格中添加下拉列表:
Vector rowdata=new Vector();
//建立一個表模型
DefaultTableModel dtm=new DefaultTableModel(rowdata,columnNames);
//通過表模型初始化一個表
JTable table=new JTable(dtm);
//向表中添加一行爲空值的行
dtm.addRow(new Vector());
//初始化一個滾動面板
JScrollPane jspanel = new JScrollPane();
//將表添加到滾動面板中
jspanel.add(table);
//將表中滾動面板中設置可見
jspanel.setViewportView(table);
//初始化下拉列表
JComboBox cb=new JComboBox(value1);
//將表的第一列設置爲下拉列表
TableColumn column = table.getColumnModel().getColumn(0);
//構造一個表單元格的默認編輯器
DefaultCellEditor editor = new DefaultCellEditor(cb);
//指定開始編輯所需的單擊次數
editor.setClickCountToStart(2);
//設置編輯此列中單元格時所用的編輯器
column.setCellEditor(editor);
//將滾動面板添加到窗口中
this.add(jspanel,BorderLayout.CENTER);
表中添加下拉列表如上圖所示。
重繪表,有刷新的效果,單是與之前的表模型不是同一個了。
//用新的行 Vector(dataVector)替換當前的 dataVector 實例變量。 //dataVector表中的數據,columnIdentifiers表頭 dtm.setDataVector(dataVector, columnIdentifiers);
//將窗口設置爲居中
frame.setLocationRelativeTo(null);