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

Monday, December 30, 2013

Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs (SEI Series in Software Engineering)

“A must-read for all Java developers. . . . Every developer has a responsibility to author code that is free of significant security vulnerabilities. This book provides realistic guidance to help Java developers implement desired functionality with security, reliability, and maintainability goals in mind.”
–Mary Ann Davidson, Chief Security Officer, Oracle Corporation  
Organizations worldwide rely on Java code to perform mission-critical tasks, and therefore that code must be reliable, robust, fast, maintainable, and secure. Java™ Coding Guidelines brings together expert guidelines, recommendations, and code examples to help you meet these demands.

Written by the same team that brought you The CERT® Oracle ® Secure Coding Standard for Java™, this guide extends that previous work’s expert security advice to address many additional quality attributes.

You’ll find 75 guidelines, each presented consistently and intuitively. For each guideline, conformance requirements are specified; for most, noncompliant code examples and compliant solutions are also offered. The authors explain when to apply each guideline and provide references to even more detailed information.

Reflecting pioneering research on Java security, Java™ Coding Guidelines offers updated techniques for protecting against both deliberate attacks and other unexpected events. You’ll find best practices for improving code reliability and clarity, and a full chapter exposing common misunderstandings that lead to suboptimal code.


With a Foreword by James A. Gosling, Father of the Java Programming Language


Sunday, December 29, 2013

Detect selection on individual cell in JTable

Last post of "Java Swing JTable and ListSelectionListener" implement MyListSelectionListener() for listSelectionModel. It can be noticed from the demo video that if click on another cell in the same row, MyListSelectionListener() will not be called.

In this post, two seperated ListSelectionListener, MyRowListener and MyColListener, are implemented and added to jTable.getSelectionModel() and jTable.getColumnModel().getSelectionModel(), to monitor individual cell selected .

Detect selection on individual cell in JTable
Detect selection on individual cell in JTable

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Label;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

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

    Label labelInfo;
    JTable jTable;
    ListSelectionModel listSelectionModel;
    
    static final String DayOfWeek[] = {
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday"};
    
    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}};

    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(tableData, DayOfWeek);
        jTable.setMaximumSize(new Dimension(10,10));

        listSelectionModel = jTable.getSelectionModel();
        jTable.getSelectionModel()
                .addListSelectionListener(new MyRowListener());
        jTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(new MyColListener());
        jTable.setSelectionModel(listSelectionModel);

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

        labelInfo = new Label();

        vPanel.add(labelInfo);
        
        getContentPane().add(vPanel, BorderLayout.CENTER);
    }
    
    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();
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyRowListener: " 
                        + row + " : " + col + " = " + selectedItem);
            }
        }
    }
    
    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();
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyColListener: " 
                        + row + " : " + col + " = " + selectedItem);
            }
        }
    }
}



Next: JTable with TableModel