Tuesday, December 31, 2013

JTable with TableModel

In this example, we will implement our TableModel for JTable, and also fix bugs in last example. It can be eddited, its column can be moved, the data in our TableModel will be updated after changed, and also implement a button to print all the updated result in System.out.

JTable with TableModel
JTable with TableModel 

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyFrame extends JFrame {

    Label labelInfo;
    JTable jTable;

    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        
        JPanel vPanel = new JPanel();
        vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS));
        
        jTable = new JTable(new MyTableModel());
        jTable.getSelectionModel()
                .addListSelectionListener(new MyRowListener());
        jTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(new MyColListener());

        jTable.setFillsViewportHeight(true);
        JScrollPane jScrollPane = new JScrollPane(jTable);
        jScrollPane.setPreferredSize(new Dimension(450, 100));
        vPanel.add(jScrollPane);

        labelInfo = new Label();
        vPanel.add(labelInfo);
        
        Button buttonPrintAll = new Button("Print All");
        buttonPrintAll.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println();
                for(int i=0; i<jTable.getRowCount(); i++){
                    for(int j=0; j<jTable.getColumnCount(); j++){
                        String val = String.valueOf(jTable.getValueAt(i, j));
                        System.out.print(val + "\t");
                    }
                    System.out.println();
                }
            }
        });
        
        getContentPane().add(vPanel, BorderLayout.CENTER);
        getContentPane().add(buttonPrintAll, BorderLayout.PAGE_END);
    }
    
    private class MyRowListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {

            if (!e.getValueIsAdjusting()) {
                System.out.println("valueChanged: " + e.toString());
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                
                /*
                // cannot access getValueAt(row, col) here...!
                // Otherwise ArrayIndexOutOfBoundsException when move column
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyRowListener: " 
                        + row + " : " + col + " = " + selectedItem);
                */
                labelInfo.setText("MyRowListener: " + row + " : " + col);

            }
        }
    }
    
    private class MyColListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {

            if (!e.getValueIsAdjusting()) {
                System.out.println("valueChanged: " + e.toString());
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                
                /*
                // cannot access getValueAt(row, col) here...!
                // Otherwise ArrayIndexOutOfBoundsException when move column
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyColListener: " 
                        + row + " : " + col + " = " + selectedItem);
                */
                labelInfo.setText("MyRowListener: " + row + " : " + col);

            }
        }
    }
    
    class MyTableModel extends AbstractTableModel {
        private String[] DayOfWeek = {
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday"};
    
        private Object[][] tableData = {
            {1, 2, 3, 4},
            {4, 3, 2, 1},
            {12, 20, 13, 14},
            {13, 29, 23, 24},
            {2, 4, 6, 8},
            {11, 21, 33, 4}};

        @Override
        public int getColumnCount() {
            return DayOfWeek.length;
        }

        @Override
        public int getRowCount() {
            return tableData.length;
        }

        @Override
        public String getColumnName(int col) {
            return DayOfWeek[col];
        }

        @Override
        public Object getValueAt(int row, int col) {
            return tableData[row][col];
        }

        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            tableData[row][col] = value;
            fireTableCellUpdated(row, col);
        }

    }
}


More:
- Display JTable data in line chart using JComponent

No comments:

Post a Comment