当前位置: 代码迷 >> J2SE >> Jtable中设置了最后一列是Button,如何给这个Button加入时间响应呢
  详细解决方案

Jtable中设置了最后一列是Button,如何给这个Button加入时间响应呢

热度:105   发布时间:2016-04-24 14:40:30.0
Jtable中设置了最后一列是Button,怎么给这个Button加入时间响应呢?
在Renderer中是这样写的

public   Component   getTableCellRendererComponent(JTable   table,   Object   value,
boolean   isSelected,   boolean   hasFocus,   int   row,   int   column)   {
if(column   ==   col){
if(value   ==   null){
return   null;
}
JButton   button   =   new   JButton((String)value);
button.addActionListener(new   ActionListener(){

public   void   actionPerformed(ActionEvent   e)   {
System.out.println( "Hello~~~ ");
}

});
return   button;
}


JTable中已经可以看到Button,但是Button没反应,请问如何解决?

------解决方案--------------------
应该是建一个类:
static class ButtonColumn extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {
JButton renderButton;
JButton editButton;
String text;
ButtonColumn() {
renderButton = new JButton();
editButton = new JButton();
editButton.setFocusPainted(false);
}

public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (hasFocus) {
renderButton.setForeground(table.getForeground());
renderButton.setBackground(UIManager
.getColor( "Button.background "));
} else if (isSelected) {
renderButton.setForeground(table.getSelectionForeground());
renderButton.setBackground(table.getSelectionBackground());
} else {
renderButton.setForeground(table.getForeground());
renderButton.setBackground(UIManager
.getColor( "Button.background "));
}

renderButton.setText((value == null) ? " " : value.toString());
return renderButton;
}

public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
text = (value == null) ? " " : value.toString();
editButton.setText(text);
return editButton;
}

public Object getCellEditorValue() {
return text;
}
}


ButtonColumn btnCol = new ButtonColumn();
table.getColumn( "321 ").setCellEditor(btnCol);
table.getColumn( "321 ").setCellRenderer(btnCol);
  相关解决方案