How to implement JButton in JTable?

UPDATED: 31 May 2013
I was working on Inventory management project where i have to place button on jTable that shows order. I googled and found solution but he didn't provided proper information with all code. I'm gonna explain it properly with all basic code.

jTable, jButton
jTable - jButton

Source : http://tips4java.wordpress.com/2009/07/12/table-button-column/
Download : http://www.camick.com/java/source/ButtonColumn.java
                      - Download the ButtonColumn.java class file and place it in proper package. Don't forget to include your package in starting of code.

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...
}

Now lets have a look on code snippet to handle the button click event. We find the button row index onclick and get the value from InvoiceArray by matching index.

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!");
            }
        }
};

0 comments :