How can I put a JCheckbox on a JTable?

混江龙づ霸主 提交于 2019-12-11 14:39:03

问题


How can I put a JCheckbox or a JButton on a specific row and column of a JTable?


回答1:


Not sure about a button, but here is a working example to put a checkbox:

import javax.swing.*;
import javax.swing.table.*;

public class Test {
  public static void main(String [] args) throws Exception {
    DefaultTableModel model = new DefaultTableModel(null, new String [] {"CheckMe", "Value"}) {
                                public Class getColumnClass(int c) {
                                  switch (c) {
                                    case 0: return Boolean.class;
                                    default: return String.class;
                                  }   
                                } };
    JTable table = new JTable(model);
    JFrame frame = new JFrame("CheckBox Test");
    frame.add(table);
    model.addRow(new Object [] {true, "This is true"});
    model.addRow(new Object [] {false, "This is false"});
    frame.pack(); frame.validate();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}



回答2:


As you can tell from khachik's answer support for a check box is provided by a table based on the column class of the column.

However, if you only want a check box on a specific row of a specific column then you need to override the getCellRenderer(...) and getCellEditor(...) methods to return the renderer/editor for the given cell. Something like:

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

    if (modelColumn == 1 && row < 3)
        return getDefaultEditor(Boolean.class);
    else
        return super.getCellEditor(row, column);
}



回答3:


For check boxes: Here and here you will find working example.

For buttons: here and here you will find working example.




回答4:


For that, you'll have to write a TableCellRenderer and a TableCellEditor.

You can derive from default swing implementations to make it easier.

In each class, you'll have to override the one method of these interfaces, and in it, check the passed row and column arguments; if both row and column match your criteria, then return a JCheckBox or a JButton, otherwise return the JComponent returned by the super implementation (when using default swing implementations of these interfaces).



来源:https://stackoverflow.com/questions/5594639/how-can-i-put-a-jcheckbox-on-a-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!