是否可以在 JTable 单元格中添加按钮以及数据?我要做的是创建一个表格,其中包含显示数据库中的数据(数字)的列,以及两个按钮来增加/减少同一单元格内的数字。
|身份证号| 数量|
|06| 2 [+][-] |
就像上面那样,[+][-] 是按钮。因此,当我按 [+] 时,如果按 [-],数字将变为 3 和 1。
是的,这是可能的,尽管这并不容易。
这是我在 5 分钟内制作的示例:
它远非完美,但显示了这个概念。
这是源代码:
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;
}
}
如果您想在单元格中显示除文本(或数字)以外的任何其他内容,我认为您需要创建一个自定义单元格渲染器。单元格渲染器的工作是绘制您需要在单元格中显示的任何内容。
请参阅表渲染器文档。
因此,在这种情况下,您可以创建一个小型 JPane,其中包含文本字段和微小的 + 和 - 按钮 - 或者只是一个 JSpinner 组件,如果您需要的话。有点棘手,当然,但应该是可能的。