2

嗨,我有一个名为 ColorChooser 的类(在 net.java.dev.colorchooser.ColorChooser 包中)

这是一个用于选择颜色的自定义组件。我想要的是在第二列中显示一个带有 ColorChooser 的 JTable。所以我创建了自己的 TableCellRenderer 并且它可以工作:

@SuppressWarnings("serial")
class ColorChooserTableRenderer extends DefaultTableCellRenderer {

    public static List<ColorChooser> colors;

    public ColorChooserTableRenderer(int rows) {
        colors = new ArrayList<ColorChooser>(rows);
        for (int i = 0; i<rows ; i ++) {
            colors.add(new ColorChooser());
        }
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        return colors.get(row);
    }

}

我在我的表中注册了这个:

JTable t = new JTable(5,3);
t.getColumn(t.getColumnName(1)).setCellRenderer(new ColorChooserTableRenderer(5));

显示器很好。当我将鼠标悬停在其中一个上时,它甚至会显示 ColorChoosers 的工具提示。问题是 ColorChoosers 没有收到 MouseEvents。

通常,当您在 ColorChooser 上按住鼠标时,会弹出一个窗口,您可以使用它来选择颜色。在 JTable 中时,ColorChooser 组件不接收鼠标事件。

有什么解决办法吗?

编辑:这个问题可以很容易地修改为:

你能给我一个在第二列中包含实际工作的 JButtons 的表的小例子吗?你知道,可以按下的按钮吗?

4

2 回答 2

3

这听起来有点熟悉,因为我一直在将表格单元格渲染器用于其他目的。

我的理解是 TableCellRenderer 只是用来渲染组件的;组件实际上并不存在于每个单元中。

因此,您可能不得不以某种方式将鼠标事件从 JTable 本身转发到 ColorChooser。

edit: p.s., see my question -- also for custom table cell rendering, you only need 1 instance of the component itself for the entire column, if the column is rendered with the same logic. Don't store persistent state in the TableCellRenderer, store it in the TableModel instead, and use that state immediately prior to rendering when you handle the call to getTableCellRendererComponent().

于 2009-05-20T13:33:06.900 回答
2

A renderer only paints the component on the screen and does not allow for interaction. What you need is to also implement a TableCellEditor. It is recommend that you inherit the AbstractCellEditor and you'll save some work. Check out the java tutorial for tables.

Example:

public class MyTableCellRenderer implements TableCellRenderer
{
    private JButton button = new JButton("Press Me");
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        return button;
    }
}

public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor
{
    private JButton button;

    public MyTableCellEditor()
    {
        button = new JButton("Press Me");
        button.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                System.out.println("buttonPressed");
            }
        });
    }
    public Object getCellEditorValue() {
        return null;
    }
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        return button;
    }
}
于 2009-05-20T13:48:38.460 回答