I want to create a JTable
cell consisting of a text field and a button, and here is where I am: I create a cell renderer like below,
public class ButtonTextFieldCellRenderer extends JPanel implements TableCellRenderer, ActionListener {
private JTextField t;
private JButton b;
public ButtonTextFieldCellRenderer(){
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
t = new JTextField(50);
t.setPreferredSize(new Dimension(50,16));
add(t);
b = new JButton("...");
b.setPreferredSize(new Dimension(16,16));
b.addActionListener(this);
add(b);
add(Box.createHorizontalGlue());
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
if (isSelected)
setBackground( table.getSelectionBackground() );
else
setBackground( table.getBackground() );
return this;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() instanceof JButton){
JOptionPane.showConfirmDialog(this, "you clicked a button", "Info", JOptionPane.CLOSED_OPTION);
}
}
}
It appear some kinds of what I wanted, a text field and an associated button as a table cell, but I have one issue: When I double click the field, the text field occupies the whole cell, and the button disappears.
I think I need to write a customized cell editor too but don't know how. Anyone care to shed a light on this?