2013-11-25 2 views
0

Любой может помочь мне понять, почему этот код не показывает значок флажка вместо текста? Я пытался найти вещи в Интернете об этом, но не нашли ничего :(CheckBox - новый Boolean (true/false)

JTabbedPane tabProcessamentoSalarial = new JTabbedPane(JTabbedPane.TOP); 
tabbedPane.addTab("Remunera\u00E7\u00F5es", null, tabProcessamentoSalarial, null); 

JPanel pnlAcumulados = new JPanel(); 
tabProcessamentoSalarial.addTab("Acumulados", null, pnlAcumulados, null); 
pnlAcumulados.setLayout(null); 

String[] columnAcumulados = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"}; 
Object[][] dataAcumulados = { 
     {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)}, 
     {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)}, 
     {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)}, 
     {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)}, 
     {"Joe", "Brown", "Pool", new Integer(10), new Boolean(true)} 
}; 

JTable tblAcumulados = new JTable(dataAcumulados, columnAcumulados); 

JScrollPane scrollPaneAcumulados = new JScrollPane(tblAcumulados); 
tblAcumulados.setFillsViewportHeight(true); 

tblAcumulados.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); 
scrollPaneAcumulados.setBounds(46, 36, 508, 160); 
pnlAcumulados.add(scrollPaneAcumulados); 

enter image description here

+0

Где проблема в коде? Просто совет, не используйте 'new Integer (10)' просто поместите '10' и в' new Boolean (true) 'just use или' true' или 'Boolean.TRUE' и не используйте' null' макет, swing был разработан для использования с менеджерами макета – nachokk

+0

Если я использую только «истину», это просто покажет мне ... «true» вместо выбранного флажка. – subrui

+0

Чтобы лучше помочь, опубликуйте [SSCCE] (http://sscce.org/). –

ответ

1

Я вижу, что вы пытаетесь следовать Oracle How to Use Tables.

К сожалению, примеры не очень понятны.

Если вы используете источник String и Object [], вы не получите флажок. Вы получите текст, как вы узнали.

Вы должны использовать TableModel для Swing для распознавания логических полей и отображения флажка. В большинстве случаев работает DefaultTableModel.

Вот Oracle example. Я не думаю, что это очень хорошо, но у меня нет примера.

class MyTableModel extends AbstractTableModel { 
    private String[] columnNames = {"First Name", 
            "Last Name", 
            "Sport", 
            "# of Years", 
            "Vegetarian"}; 
    private Object[][] data = { 
    {"Kathy", "Smith", 
    "Snowboarding", new Integer(5), new Boolean(false)}, 
    {"John", "Doe", 
    "Rowing", new Integer(3), new Boolean(true)}, 
    {"Sue", "Black", 
    "Knitting", new Integer(2), new Boolean(false)}, 
    {"Jane", "White", 
    "Speed reading", new Integer(20), new Boolean(true)}, 
    {"Joe", "Brown", 
    "Pool", new Integer(10), new Boolean(false)} 
    }; 

    public int getColumnCount() { 
     return columnNames.length; 
    } 

    public int getRowCount() { 
     return data.length; 
    } 

    public String getColumnName(int col) { 
     return columnNames[col]; 
    } 

    public Object getValueAt(int row, int col) { 
     return data[row][col]; 
    } 

    /* 
    * JTable uses this method to determine the default renderer/ 
    * editor for each cell. If we didn't implement this method, 
    * then the last column would contain text ("true"/"false"), 
    * rather than a check box. 
    */ 
    public Class getColumnClass(int c) { 
     return getValueAt(0, c).getClass(); 
    } 

    /* 
    * Don't need to implement this method unless your table's 
    * editable. 
    */ 
    public boolean isCellEditable(int row, int col) { 
     //Note that the data/cell address is constant, 
     //no matter where the cell appears onscreen. 
     if (col < 2) { 
      return false; 
     } else { 
      return true; 
     } 
    } 

    /* 
    * Don't need to implement this method unless your table's 
    * data can change. 
    */ 
    public void setValueAt(Object value, int row, int col) { 
     if (DEBUG) { 
      System.out.println("Setting value at " + row + "," + col 
           + " to " + value 
           + " (an instance of " 
           + value.getClass() + ")"); 
     } 

     data[row][col] = value; 
     fireTableCellUpdated(row, col); 

     if (DEBUG) { 
      System.out.println("New value of data:"); 
      printDebugData(); 
     } 
    } 

    private void printDebugData() { 
     int numRows = getRowCount(); 
     int numCols = getColumnCount(); 

     for (int i=0; i < numRows; i++) { 
      System.out.print(" row " + i + ":"); 
      for (int j=0; j < numCols; j++) { 
       System.out.print(" " + data[i][j]); 
      } 
      System.out.println(); 
     } 
     System.out.println("--------------------------"); 
    } 
} 
0

Как АКФ указал here, просто создать новый класс:

общественный класс CheckBoxRenderer расширяет JCheckBox реализует TableCellRenderer {

 CheckBoxRenderer() { 
     setHorizontalAlignment(JLabel.CENTER); 
     } 

     public Component getTableCellRendererComponent(JTable table, Object value, 
      boolean isSelected, boolean hasFocus, int row, int column) { 
     if (isSelected) { 
      setForeground(table.getSelectionForeground()); 
      //super.setBackground(table.getSelectionBackground()); 
      setBackground(table.getSelectionBackground()); 
     } else { 
      setForeground(table.getForeground()); 
      setBackground(table.getBackground()); 
     } 
     setSelected((value != null && ((Boolean) value).booleanValue())); 
     return this; 
     } 

}

Затем, после установки модели на ваш тип стола:

CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer(); 
mytable.getColumnModel().getColumn(number_of_the_one_I_want).setCellRenderer(checkBoxRenderer); 
Смежные вопросы