문제

I'm making a custom TableModel usingAbstractTableModelfor a project, and I need to figure out a way to have a checkbox show up on some rows, but not others. I have already implemented a getColumn method, but I want to be able to have a checkbox not show up unless a certain condition in another column is reached (for example, if the object represented by a particular row is a lightbulb rather than, say, a toaster, give the user a checkbox to turn the light on or off).

I've tried using getValueAt and passing null or a string instead of a Boolean object in the hopes that maybe Swing wouldn't render the checkbox. And it doesn't, but it also throws a nasty set of ClassCastExceptions for trying to cast a String to a Boolean.

Does anyone have any ideas on how I could do something like this?

도움이 되었습니까?

해결책

Columns in a Swing JTable are displayed using cell renderers. You should read How to Use Tables in the Java tutorials which has a section that describes how the mechanism works. This is how the core method of a custom cell renderer looks like:

public Component getTableCellRendererComponent(JTable table, Object color,
                        boolean isSelected, boolean hasFocus,
                        int row, int column) {

The task of this method is to select and prepare a Component (by setting desired colors, fonts, images...) for a specific row and column that the framework will use paint on to its Graphics context. There is a DefaultTableCellRenderer that might do the trick without too much custom code (see the tutorial). Note that this rendering mechanism is an optimization chosen by the Swing developers.

You can also learn a lot about customizing Swing components in Swing Hacks. The examples are not especially well-designed code but just show how to make creative use of the Swing API.

Good luck!

Example (see comments):

    final JTable orderTable = new JTable(dataModel);
    // All columns with class Boolean are renderered with MyFancyItemRenderer
    orderTable.setDefaultRenderer(Boolean.class, new MyFancyItemRenderer());

    // Setting the cell renderers explicitly for each column
    final TableColumnModel columnModel = orderTable.getColumnModel();

    final TableColumn itemCountColumn = columnModel.getColumn(ITEM_COUNT);
    itemCountColumn.setCellRenderer(new MyFancyItemRenderer());

    // ...

    final TableColumn sumColumn = columnModel.getColumn(SUM);
    sumColumn.setCellRenderer(new MyFancyPriceRenderer());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top