簡體   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