Posted on 2008-03-02 00:16
kooyee 閱讀(1048)
評論(0) 編輯 收藏 所屬分類:
Swing/Applet
使用到自定義的
CellRenderer和 CellEditor. 它們以作為inner class加入到table所在的class中
定義一個cell的Jbutton渲染對象

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;
}
}
定義button cell editor

class ButtonEditor extends DefaultCellEditor
{
protected JButton button;

private String label;

private boolean isPushed;
private String selectId;


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);
//get the value of the first cell in this selected row
selectId = table.getValueAt(row, 0).toString();
isPushed = true;
return button;
}


//這里是點擊button執行的操作
public Object getCellEditorValue()
{

if (isPushed)
{
JOptionPane.showMessageDialog(null, "The first of this row is"+selectId, "", JOptionPane.ERROR_MESSAGE);
}
isPushed = false;
return new String(label);
}


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


protected void fireEditingStopped()
{
super.fireEditingStopped();
}
}
最后在table中加入他們, 假設添加到table中名為"button"的列
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor( new ButtonEditor(new JCheckBox()));