如何正确使用setCellRenderer?

时间:2013-08-20 16:17:13

标签: java swing jtable jprogressbar tablecellrenderer

现在我有了这段代码

jTable1.getColumn("Progress").setCellRenderer(new TableCellRenderer() {

    @Override
    public Component getTableCellRendererComponent(JTable arg0, Object arg1,
    boolean arg2, boolean arg3, int arg4, int arg5) {
        // TODO Auto-generated method stub
        return new JProgressBar();
    }
});

我想继续更新它的进度,但当然这段代码不起作用。

所以我把它改成了这个。

jTable1.getColumn("Progress").setCellRenderer(new TableCellRenderer() {

    @Override
    public Component getTableCellRendererComponent(JTable arg0, Object arg1,
    boolean arg2, boolean arg3, int arg4, int arg5) {
        // TODO Auto-generated method stub
        JProgressBar bar2 = bar; //where bar is another JProgressBar being updated outside.
        return bar2;
    }
});

此代码有效,但问题是,当有多行时,它们的列都会更新为相同的值,这不是我想要的。

我希望能够更新个别行的JProgressBar,但我该怎么做?

1 个答案:

答案 0 :(得分:1)

我做过类似的事情(JSpinner而不是JProgressBar)我已经这样做了:

public class SpinnerRenderer implements TableCellRenderer {
    private JSpinner spinner = new JSpinner();

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

        checkNotNull(model, "The SpinnerModel from the table model is null");

        if (!(value instanceof SpinnerModel)) {
            System.err.println("Error: The value" + " in cell: row=" + row
                    + " col=" + column + " must be instance"
                    + " of SpinnerModel");
        }else{
            SpinnerModel model = (SpinnerModel)value;
            spinner.setModel(model);
        }

        return spinner;
    }

}

您应该注意我从表模型中获取数据,其中每个微调器都有单独的SpinnerModel。