繁体   English   中英

将jbutton添加到jtable的更简单方法

[英]simplier way to add jbutton to jtable

好吧,我正在制作一个有表格的系统,我必须在最后一栏中放置按钮。 我一直在研究,但我看到的所有代码确实令人困惑。 有一个,但是还有一些我不理解的部分。 这是我得到它的网站http://www.javaquery.com/2013/05/how-to-implement-jbutton-in-jtable.html

String[] InvoiceArray = new String[20];
//Declare above variable globally. Used by two-three methods. Change variable name as per your need.

/* 
 * import the ButtonColumn class if you are not working in IDE
 * I used formWindowOpened event to load content in Jtable but you can use other event.
 * All you need is put the code with in that event.
 */
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[4][2]; // 4: is number of row ; 2: is number of column
        Object columnNames[] = {"Invoice No", "View Report"}; // Name of columns
        for (int i = 0; i < 4; i++) {
            InvoiceArray[i] = i + "-2345";
            rowData[i][0] = i + "-2345";
            rowData[i][1] = "View Order " + i; // Can change the text of button.
        }
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
        jTable1.setModel(tm);
        ButtonColumn buttonColumn = new ButtonColumn(jTable1, showOrder, 1); // 1: is column number. column count starts with 0,1,2...
}

InvoiceArray有什么用? 我应该从最后一行开始showOrder吗? 而且,我不理解他发布的如何使其成为听众的代码。 这里是:

Action showOrder = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
       //JTable table = (JTable) e.getSource(); // If you have multiple component following the ActionEvent
            int modelRow = Integer.valueOf(e.getActionCommand());
            if (InvoiceArray[modelRow] != null) {
                /* We are placing invoice no in array 
                 * And track the button click index
                 * And fetch index in invoice no
                 */
                System.out.println("Your Invoice No:" + InvoiceArray[modelRow]);
            } else {
                JOptionPane.showMessageDialog(rootPane, "No records found!");
            }
        }
};

我知道已经有一些解释了。 我了解其中一些,但不是全部。 只是在jtable上添加jbutton以及为jbutton侦听器的一种简单方法。 非常感谢

只是在jtable上添加jbutton以及为jbutton侦听器的一种简单方法。

没有简单的方法。 您需要了解渲染器和编辑器在JTable中的工作方式。 阅读Swing教程中有关“ 概念:渲染器和编辑器”的部分 ,以了解基础知识。

然后,您可以签出“ 表格按钮列” ,它为您做了辛苦的工作。 您只需要提供单击按钮时要调用的Action

InvoiceArray有什么用?

它用于将数据加载到JTable中。 这是JTable的基本用法,与向表的列中添加按钮绝对无关。

加载数据后,您应该忘记invoiceArray。 您编写的Action应该通过TableModel或JTable访问数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM