2010-11-29 147 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具有完整的可運行示例。

相關問題