在JTable的单元格中添加按钮和数据? [英] Adding Buttons inside cell of JTable along with data?

查看:147
本文介绍了在JTable的单元格中添加按钮和数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在JTable单元格中添加按钮以及数据?
我要做的是创建一个表,其中包含显示数据库中数据(数字)的列,以及两个按钮,用于增加/减少同一单元格内的数字。



| ID |数量|

| 06 | 2 [+] [ - ] |



如上所述,[+] [ - ]为按钮。因此,当我按[+]时,如果按[ - ],数字将变为3和1.

解决方案

是的,它是可能的,虽然这并不容易。



您必须编写自己的自定义和这里


Is it possible to add buttons inside the JTable cell along with data? What I am trying to 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.

这篇关于在JTable的单元格中添加按钮和数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆