2010-11-29 117 views

回答

0

您需要添加自定义单元格渲染器,当按钮状态更改时,重定位表格中的一些事件并重新绘制单元格。这是邪恶的,它是讨厌的,但它可以做到。

+0

伟大的人,我发现它....非常感谢您的帮助! – Jasra 2010-11-30 09:48:10

0

Button Table Example所示,我们将创建一个类JButton并实现TableCellRenderer

class ButtonRenderer extends JButton implements TableCellRenderer { 

    public ButtonRenderer() { 
    setOpaque(true); 
    } 

    public Component getTableCellRendererComponent(JTable table, Object value, 
     boolean isSelected, boolean hasFocus, int row, int column) { 
    if (isSelected) { 
     setForeground(table.getSelectionForeground()); 
     setBackground(table.getSelectionBackground()); 
    } else { 
     setForeground(table.getForeground()); 
     setBackground(UIManager.getColor("Button.background")); 
    } 
    setText((value == null) ? "" : value.toString()); 
    return this; 
    } 
} 

然后您需要为该列创建一个单元格编辑器。

class ButtonEditor extends DefaultCellEditor { 
    protected JButton button; 

    private String label; 

    private boolean isPushed; 

    public ButtonEditor(JCheckBox checkBox) { 
    super(checkBox); 
    button = new JButton(); 
    button.setOpaque(true); 
    button.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
     fireEditingStopped(); 
     } 
    }); 
    } 

    public Component getTableCellEditorComponent(JTable table, Object value, 
     boolean isSelected, int row, int column) { 
    if (isSelected) { 
     button.setForeground(table.getSelectionForeground()); 
     button.setBackground(table.getSelectionBackground()); 
    } else { 
     button.setForeground(table.getForeground()); 
     button.setBackground(table.getBackground()); 
    } 
    label = (value == null) ? "" : value.toString(); 
    button.setText(label); 
    isPushed = true; 
    return button; 
    } 

    public Object getCellEditorValue() { 
    if (isPushed) { 
     // 
     // 
     JOptionPane.showMessageDialog(button, label + ": Ouch!"); 
     // System.out.println(label + ": Ouch!"); 
    } 
    isPushed = false; 
    return new String(label); 
    } 

    public boolean stopCellEditing() { 
    isPushed = false; 
    return super.stopCellEditing(); 
    } 

    protected void fireEditingStopped() { 
    super.fireEditingStopped(); 
    } 
} 

然后,我们将设置ButtonRender的实例作为细胞呈现该列和单元格编辑器ButtonEditor的一个实例。

\\"Button" is the column name 
table.getColumn("Button").setCellRenderer(new ButtonRenderer()); 
table.getColumn("Button").setCellEditor(
    new ButtonEditor(new JCheckBox())); 

提供的链接中的example具有完整的可运行示例。

相关问题