2015-10-02 47 views
0

作爲項目的一部分,我希望爲每個單元製作不同類型對象的表格,但我無法理解如何使每個單元格都自定義......我發現here如何設置列它有一個像String,Bool,Slider這樣的對象類型......但是對於每個Cell我都不知道!自定義表格原始對象

這幅畫是從jformDesigner軟件性能的一部分,我想是這樣的表:

enter image description here

+0

可你也發表您的代碼更好的理解? – sifho

+0

我使用本網站的代碼:http://www.java2s.com/Code/Java/Swing-JFC/Asliderrendererforvolumevaluesinatable.htm – M410

回答

2

這個例子可以作爲一個起點:

import java.awt.*; 
import java.util.*; 
import javax.swing.*; 
import javax.swing.event.*; 
import javax.swing.table.*; 

public class TablePropertyEditor extends JFrame 
{ 
    public TablePropertyEditor() 
    { 
     String[] columnNames = {"Type", "Value"}; 
     Object[][] data = 
     { 
      {"String", "I'm a string"}, 
      {"Date", new Date()}, 
      {"Integer", new Integer(123)}, 
      {"Double", new Double(123.45)}, 
      {"Boolean", Boolean.TRUE} 
     }; 

     JTable table = new JTable(data, columnNames) 
     { 
      private Class editingClass; 

      public TableCellRenderer getCellRenderer(int row, int column) 
      { 
       editingClass = null; 
       int modelColumn = convertColumnIndexToModel(column); 

       if (modelColumn == 1) 
       { 
        Class rowClass = getModel().getValueAt(row, modelColumn).getClass(); 
        return getDefaultRenderer(rowClass); 
       } 
       else 
        return super.getCellRenderer(row, column); 
      } 

      public TableCellEditor getCellEditor(int row, int column) 
      { 
       editingClass = null; 
       int modelColumn = convertColumnIndexToModel(column); 

       if (modelColumn == 1) 
       { 
        editingClass = getModel().getValueAt(row, modelColumn).getClass(); 
        return getDefaultEditor(editingClass); 
       } 
       else 
        return super.getCellEditor(row, column); 
      } 

      // This method is also invoked by the editor when the value in the editor 
      // component is saved in the TableModel. The class was saved when the 
      // editor was invoked so the proper class can be created. 

      public Class getColumnClass(int column) 
      { 
       return editingClass != null ? editingClass : super.getColumnClass(column); 
      } 
     }; 

     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     JScrollPane scrollPane = new JScrollPane(table); 
     getContentPane().add(scrollPane); 
    } 

    public static void main(String[] args) 
    { 
     TablePropertyEditor frame = new TablePropertyEditor(); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
} 
+0

感謝您的幫助...我也想在一些單元格中添加滑塊!這樣有可能嗎? – M410

+0

這是一個需要進一步擴展的簡單示例。首先你需要創建一個「滑塊編輯器」(我從來沒有做過)。然後你需要修改代碼來使用這個編輯器。所以也許你需要一個HashMap 。然後,在使用基於類的編輯器之前,您將首先查看此表。 – camickr

+0

我不認爲這是做到這一點的正確方法!正如我在圖片中看到的那樣,有很多項目是定製的......可能有更好的方法來做到這一點 – M410