Adding Buttons inside cell of JTable along with data?
Is it possible to add buttons inside the JTable cell along with data? What I am trying t开发者_StackOverflowo do is to create a table with columns which display data(number) from the database, and two buttons to increase/decrease the number inside the same cell.
|ID | Quantity|
|06| 2 [+][-] |it would be something like above with [+][-] being buttons. So when I press [+], the number will change to 3 and 1 if pressing [-].
Yes, it is possible, although It won't be easy.
You have to write your own custom cell renderer and your own cell editor.
This is a sample I made in 5 minutes:
It is far from perfect, but shows the concept.
Here's the source code:
import java.awt.Component;
import java.awt.Font;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.Dimension;
public class CustomCell {
public static void main( String [] args ) {
Object [] columnNames = new Object[]{ "Id", "Quantity" };
Object [][] data = new Object[][]{ {"06", 1}, {"08", 2} };
JTable table = new JTable( data, columnNames ) {
public TableCellRenderer getCellRenderer( int row, int column ) {
return new PlusMinusCellRenderer();
}
};
table.setRowHeight( 32 );
showFrame( table );
}
private static void showFrame( JTable table ) {
JFrame f = new JFrame("Custom Cell Renderer sample" );
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.add( new JScrollPane( table ) );
f.pack();
f.setVisible( true );
}
}
class PlusMinusCellRenderer extends JPanel implements TableCellRenderer {
public Component getTableCellRendererComponent(
final JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
this.add( new JTextField( value.toString() ) );
this.add( new JButton("+"));
this.add( new JButton("-"));
return this;
}
}
Here's a thread that may be interesting and here.
As discussed in the tutorial you'll need both a renderer to display your value and an editor to detect events from the cell being edited. In this example, the Component
is a JCheckBox
. Note that this requires a custom DataModel
that extends AbstractTableModel
to supply the correct Class
for a given column. Joonas' suggestion to use JSpinner
is a good one that works well.
I think you need to create a custom cell renderer if you want to show anything else than text (or numbers) in the cell. The cell renderer's job is to paint whatever you need to show in the cell.
See Table Renderer documentation.
So in this case you could create a small JPane which contains the text field and the tiny + and - buttons - or a just a JSpinner component, if does what you need. A bit tricky, for sure, but should be possible.
精彩评论