2012-05-07 154 views
0

我正在使用此代碼將JCombobox添加到JTable,但是當我運行此代碼時,沒有將組合框添加到Jtable只有標題顯示在Jtable中。將JComboBox添加到JTable

Private JTable ScrollPaneTable; 

public JTable getScrollPaneTable() 
    { 
     if(ScrollPaneTable == null) 
     { 
      try 
      { 
       ScrollPaneTable = new JTable(); 
       ScrollPaneTable.setName("ScrollPaneTable"); 
       getJScrollPane1().setColumnHeaderView(ScrollPaneTable.getTableHeader()); 
       TableColumn sportColumn = ivjScrollPaneTable.getColumnModel().getColumn(0); 
       sportColumn.setCellEditor(new DefaultCellEditor(getCombo1())); //getCombo1      
          returns the JCombo box reference whose items are already added. 
       ScrollPaneTable.setBounds(0, 0, 200, 200); 
      } 
      catch(Throwable Exc) 
      { 
       handleException(Exc); 
      } 
     } 
     return ScrollPaneTable; 
    } 

這裏我只添加一個組合,但是我想在其他列中使用更多的組合。

回答

1

郵報SSCCE,這對我的作品,

import javax.swing.DefaultCellEditor; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JTable; 
import javax.swing.table.TableColumn; 

public class TestJComboBox { 

    public static void main(String args[]) { 

     JFrame frame = new JFrame("Example of JCombobox in JTable"); 
     frame.setSize(450, 250); 

     JTable table = new JTable(5,5); 

     TableColumn testColumn = table.getColumnModel().getColumn(0); 

     JComboBox comboBox = new JComboBox(); 
     comboBox.addItem("This"); 
     comboBox.addItem("is"); 
     comboBox.addItem("a"); 
     comboBox.addItem("Sample program"); 
     comboBox.addItem("for"); 
     comboBox.addItem("StackOverflow"); 
     testColumn.setCellEditor(new DefaultCellEditor(comboBox)); 

     frame.add(table); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


     frame.setVisible(true); 
    } 
}