Wednesday, July 3, 2013

How to add scroll bar to your JScrollPane

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lee
 */

public class MyTableFrame extends JPanel {
    
    
    
    public MyTableFrame() {
        Object[][] data = {
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
        };

        String[] columnNames = new String[data[0].length];
        for(int i=0; i<data[0].length; i++) {
            columnNames[i] = "column: " + i;
        }
            
        DefaultTableModel myModel = new DefaultTableModel(data, columnNames);
        JTable myTable = new JTable(myModel);
        
        // Here, we add vertial scroll bar and horizontal scroll bar
        // VERTICAL_SCROLLBAR_ALWAYS could be VERTIAL_SCROLLBAR_AS_NEEDED 
        // same for horizontal bar
        JScrollPane myScrollPane = new JScrollPane(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        myScrollPane.getViewport().add(myTable);
        
        this.add(myScrollPane);
    }
    
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Create and set up the content pane.
        MyTableFrame newContentPane = new MyTableFrame();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
 
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
 
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
};

Monday, June 24, 2013

An Interesting post about if-else vs Switch

When I was working on if-else statements on netbeans IDE, it gave me an advice to change if-else to switch.

So I googled it why I had to use switch instead of if-else, and heres the answer

http://www.google.co.jp/url?sa=t&rct=j&q=&esrc=s&frm=1&source=web&cd=5&ved=0CFAQFjAE&url=http%3A%2F%2Fwww.ashishpaliwal.com%2Fblog%2F2009%2F08%2Fif-else-vs-switch-%25E2%2580%2593-which-is-better%2F&ei=XAbIUfm8E8ejkAWJ64CYBw&usg=AFQjCNHMSGjKS0cjY_t_rOmKqBuz7VkVEQ&sig2=hVPuZARGnOVwsh0zvc10sw&bvm=bv.48293060,d.dGI

so in short, switch has more performance and readability advantage.



Programming is fun

Found really cool array copy method

I was working on array copy menually, then my IDE netbeans gave me a warning sign.

"You are Copying Arrays Manually."

And it showed me how to do it using System.arraycopy!

I think this IDE is so awesome, and people who made it are geniuses.

I hope I could be like them someday

http://docs.oracle.com/javase/6/docs/api/java/lang/System.html

Thursday, June 20, 2013

How to change background color of a row relate to a column data

In this post, I explain how to change background color according to data of a column.

First, this is my goal.

The first row, second column is "male", and the background color of the row is light gray.

 
As I change the male to female, the background color is changed to Orange. 

 
 
I will explain this in source code.


package jtbl_color;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

/**
 *
 * @author Lee
 */
public class ColoredTable extends JPanel{
    
    private JTable table;
    private JScrollPane scrollPane;
    private MyTableModel model;
    private int sexColumn = 1;
    
    // data for the table
    private Object[][] data = {
        {"Singed", "male", false}, 
        {"Akali", "female", false},    
        {"Tristina", "female", true},    
        {"Udyr", "male", false},     
        {"Janna", "female", true}
    };
    
    // column names for the table
    private final String[] columnNames = {
        "Name", "Sex", "Vegetarian"
    };
    
    public ColoredTable() {
        super(new BorderLayout());
        initComponents();
    }
    
    public void initComponents() {
        // Initiate the Abstract Table Model
        model = new MyTableModel();
        
        // Add TableModelListener to the model
        model.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                // get the event, and check if the changed event is data update
                if(e.getType() == TableModelEvent.UPDATE) {
                    // repaint the row
                    rowRepaint(table, table.convertRowIndexToView(e.getFirstRow()));
                }
            }
        });
        // Add the model to the JTable
        table = makeTable(model);
        
        // set the Combo box to sex column
        setSexColumn(table.getColumnModel().getColumn(sexColumn));
        
        // Add the table to the JScrollPane
        scrollPane = new JScrollPane(table);
        
        // Add the scrollPane to the JPanel
        this.add(scrollPane);
    }
    
    // set combo box for sex column
    public static void setSexColumn(TableColumn sexColumn){
        // new combo box
        JComboBox comboBox = new JComboBox();
        // add male and female items to the combo box
        comboBox.addItem("male");
        comboBox.addItem("female");
        // set combo box to the sex column
        sexColumn.setCellEditor(new DefaultCellEditor(comboBox));
    }
    
    // repaint the selected row 
    private static void rowRepaint(JTable table, int row) {
        Rectangle r = table.getCellRect(row, 0, true);
        r.width = table.getWidth();
        table.repaint(r);
    }
    
    // make table for changing colors
    private JTable makeTable(final MyTableModel model) {
        return new JTable(model) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                String sex = (String)model.getValueAt(
                        convertRowIndexToModel(row), sexColumn);
                
                if(sex.equals("female")) {
                        c.setBackground(Color.ORANGE);
                    } else if (sex.equals("male")) {
                        c.setBackground(Color.LIGHT_GRAY);
                    }
                return c;
            }
        };
    }
    
    // Define the model for the table using AbstractTableModel
    class MyTableModel extends AbstractTableModel {
        // Decide the row count according to the data length   
        @Override       
        public int getRowCount() {        
            return data.length;     
        }     
        
        // decide the column count according to the columnNames length   
        @Override     
        public int getColumnCount() {      
            return columnNames.length;     
        }        
        
        // put the data values into the table.     
        @Override       
        public Object getValueAt(int rowIndex, int columnIndex) {     
            return data[rowIndex][columnIndex];    
        }               
        
        // put the columnNames values into the table column names    
        @Override      
        public String getColumnName(int col){      
            return columnNames[col];     
        }              
        
        // set if the cells in the table are editable.     
        // In this example, all the cells are editable  
        @Override      
        public boolean isCellEditable(int row, int col) {     
            return true;       
        }                
        
        // this is for data change.      
        @Override      
        public void setValueAt(Object value, int row, int col) {      
            data[row][col] = value;      
            fireTableCellUpdated(row, col);   
        }    
        /*     
         * JTable uses this method to determine the default renderer/    
         * editor for each cell.  If we didn't implement this method,       
         * then the last column would contain text ("true"/"false"),     
         * rather than a check box.  (From oracle JTable tutorial)   
         */        
        @Override
        public Class getColumnClass(int c) {        
            return getValueAt(0, c).getClass();     
        }
    }
    
    /**       
     * Create the GUI and show it.   
     * For thread safety,      
     * this method should be invoked from the    
     * event-dispatching thread.       
     * (from Oracle table tutorial)    
     */  
    private static void createAndShowGUI() {     
        //Create and set up the window.       
        JFrame frame = new JFrame("TableRenderDemo");      
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
        //Create and set up the content pane.      
        ColoredTable newContentPane = new ColoredTable();        
        newContentPane.setOpaque(true); //content panes must be opaque     
        frame.setContentPane(newContentPane);                     
        //Display the window.      
        frame.pack();      
        frame.setVisible(true);       
    }        
    public static void main(String[] args) {     
        //Schedule a job for the event-dispatching thread:   
        //creating and showing this application's GUI.      
        SwingUtilities.invokeLater(new Runnable() {        
            @Override        
            public void run() {   
                createAndShowGUI();   
            }    
        });   
    }
}

I don't remember where I saw this method, so I cannot give you the reference page.
Also, I'm not quite sure what the prepareRenderer does..
More study is required here

How to share a data among two tables

In this post, I'll explain how to share one data among two table.

First, I will define a DataContainer class that holds all the data I want.

package jtbl_2tbl_abst;


/**
 *
 * @author Lee
 */
public class DataContainer {
    
    private Object[][] data = {
        {"Singed", "male", false},
        {"Akali", "female", false},
        {"Tristina", "female", true},
        {"Udyr", "male", false},
        {"Janna", "female", true}
    };
    
    private final String[] columnNames = {
        "Name", "Sex", "Vegetarin"
    };

    /**
     * @return the data
     */
    public Object[][] getData() {
        return data;
    }

    /**
     * @param data the data to set
     */
    public void setData(Object[][] data) {
        this.data = data;
    }
    
    public void setData(Object data, int row, int col) {
        this.data[row][col] = data; 
    }

    /**
     * @return the columnNames
     */
    public String[] getColumnNames() {
        return columnNames;
    }
}

Now I want MyTableModel that extends AbstractTableModel.
(otherwise I should redefine MyTableModel for each table.)

package jtbl_2tbl_abst;

import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Lee
 */
public class MyTableModel extends AbstractTableModel {
    
    // holds column names and data from outer source
    private String[] columnNames;
    private Object[][] data;
    
    public MyTableModel(Object[][] data, String[] columnNames) {
        this.data = data;
        this.columnNames = columnNames;
    }
    

    // the explanation is ommitted since I've covered it in the last post
    // "Using AbstractTableModel"
    @Override
        public int getRowCount() {
            return data.length;
        }

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

        @Override
        public Object getValueAt(int row, int col) {
            return data[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) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }
    
}

now, let's define Table1 class

package jtbl_2tbl_abst;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import net.miginfocom.swing.MigLayout;

/**
 *
 * @author Lee
 */
public class Table1 extends JPanel implements TableModelListener{
    
    // JScrollPane that takes JTable
    private JScrollPane scrollPane;
    // This is table
    private JTable table1;
    // this holds data from DataContainer
    DataContainer container = new DataContainer();
    // this holds AbstractTableModel from MyTableModel
    private AbstractTableModel model;
    
    public Table1(DataContainer container) {
        super(new MigLayout());
        this.container = container;
        initComponents();
    }
    
    private void initComponents() {
        // initiate the table model
        model = new MyTableModel(container.getData(), container.getColumnNames());
        // initiate the table
        table1 = new JTable(model);
        // add TableModelListener so that we can change the data, and the 
        // changed data can be detected
        table1.getModel().addTableModelListener(this);
        scrollPane = new JScrollPane(table1);
        
        this.add(scrollPane);
    }

    @Override
    public void tableChanged(TableModelEvent e) {
        // get the first row that has been changed
        int row = e.getFirstRow();
        // get the column that has been changed
        int column = e.getColumn();
        // get the changed model of the table
        TableModel model = (TableModel)e.getSource();
        
        // tableChanged method throws -1 when theres no change of row and columns
        // but wants to update the whole table.
        // And that causes unexpected errors, so I put if(column >=0) to prevent that
        if(column >= 0 ) {
            String columnName = model.getColumnName(column);
            // get the changed data from the table model
            Object data = model.getValueAt(row, column);
            // apply the change to the container data
            container.setData(data, row, column);
        }
    }

    /**
     * @return the table1
     */
    public JTable getTable1() {
        return table1;
    }

    /**
     * @param table1 the table1 to set
     */
    public void setTable1(JTable table1) {
        this.table1 = table1;
    }

    /**
     * @return the model
     */
    public AbstractTableModel getModel() {
        return model;
    }

    /**
     * @param model the model to set
     */
    public void setModel(AbstractTableModel model) {
        this.model = model;
    }
}

Similarly, we need to define Table2. The explanation is omitted since Table2 is identical to Table1

package jtbl_2tbl_abst;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import net.miginfocom.swing.MigLayout;

/**
 *
 * @author Lee
 */
public class Table2 extends JPanel implements TableModelListener{

    private JScrollPane scrollPane;
    private JTable table2;
    private AbstractTableModel model;
    DataContainer container = new DataContainer();
    
    public Table2(DataContainer container) {
        super(new MigLayout());
        this.container = container;
        initComponents();
    }
    
    public void initComponents() {
        model = new MyTableModel(container.getData(), container.getColumnNames());
        table2 = new JTable(model);
        table2.getModel().addTableModelListener(this);
        
        scrollPane = new JScrollPane(table2);
        this.add(scrollPane);
    }
    
    @Override
    public void tableChanged(TableModelEvent e) {
        int row = e.getFirstRow();
        int column = e.getColumn();
        TableModel model = (TableModel)e.getSource();

        if(column >= 0 ) {
            String columnName = model.getColumnName(column);
            Object data = model.getValueAt(row, column);
            System.out.println("changed data: " + data);
            container.setData(data, row, column);
        }
    }

    /**
     * @return the table2
     */
    public JTable getTable2() {
        return table2;
    }

    /**
     * @param table2 the table2 to set
     */
    public void setTable2(JTable table2) {
        this.table2 = table2;
    }

    /**
     * @return the model
     */
    public AbstractTableModel getModel() {
        return model;
    }

    /**
     * @param model the model to set
     */
    public void setModel(AbstractTableModel model) {
        this.model = model;
    }
}

Now we need JFrame that holds the two tables.

package jtbl_2tbl_abst;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;

/**
 *
 * @author Lee
 */
public class Frame {
    
    // JFrame that holds Table1
    JFrame frame1  = new JFrame();
    // JFrame that holds Table2
    JFrame frame2 = new JFrame();
    // This button will open frame2 with Table2
    JButton opnBttn = new JButton("Open Table2");
    // This button will close frame2 updating the changed data
    JButton mdfBttn = new JButton("OK");
    // This button will Update frame2(table2) when table1 has been changed
    JButton udtBttn = new JButton("Update");
    DataContainer container = new DataContainer();
    Table1 table1Panel;
    Table2 table2Panel;
    
    public Frame() {
        initTable1();
        initTable2();
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Frame();
            }
        });
    }
    
    // initiate Table1
    public void initTable1() {
        // add ActionListener to opnBttn
        opnBttn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                opnBttnClicked(evt);
            }
        });
        
        // add ActionListener to udtBttn
        udtBttn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                udtBttnClicked(evt);
            }
        });
        
        // initiate Table1 with the sharing data
        table1Panel = new Table1(container);
        
        // setup frame1
        frame1.setLayout(new MigLayout());
        frame1.add(table1Panel, "span, growx, wrap");
        frame1.add(opnBttn);
        frame1.add(udtBttn);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.pack();
        frame1.setVisible(true);
    }
    
    // initiate Table2
    public void initTable2() {
        // add ActionListener to mdfBttn
        mdfBttn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                mdfBttnClicked(evt);
            }
        });
        
        // initiate Table2 with the sharing data
        table2Panel = new Table2(container);
        
        // set up frame2
        frame2.setLayout(new MigLayout());
        frame2.add(table2Panel, "wrap");
        frame2.add(mdfBttn, "center");
        frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame2.pack();
    }

    // when opnBttn is clicked, frame2(table2) become visible
    public void opnBttnClicked(ActionEvent evt) {
        // clikcing the opnBttn when one is editing the table cell will cause 
        // data lose since the changed value is still in Editor, not in Renderer.
        // To send the changed value from Editor to Render, I need the following
        if (table1Panel.getTable1().isEditing()) {
            table1Panel.getTable1().getCellEditor().stopCellEditing();
        }
        
        // open frame2(table2)
        frame2.setVisible(true);
    }
    
    // when mdfBttn is clicked, frame2 is closed 
    public void mdfBttnClicked(ActionEvent evt) {
        // same as above
        if (table2Panel.getTable2().isEditing()) {
            table2Panel.getTable2().getCellEditor().stopCellEditing();
        }
        frame2.setVisible(false);
        // notify table1 that the data may have been changed
        table1Panel.getModel().fireTableDataChanged();
    }
    
    // when udtBttn is clicked, table2 refreshes 
    public void udtBttnClicked(ActionEvent evt) {
        if (table1Panel.getTable1().isEditing()) {
            table1Panel.getTable1().getCellEditor().stopCellEditing();
        }
        table2Panel.getModel().fireTableDataChanged();
    }
}

How to debug

my boss taught me how to debug today, and here's the code.

Put this where error occurs.



try {
    throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}

Using AbstractTableModel

In this post, I explain how to make a JTable using AbstractTableModel

Using AbstractTableModel is very straight foward, so I will just post
a source code that one can use as a basic form like DefaultTableModel

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtbl_ex;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Lee
 */
public class TableOne extends JPanel{
    
    private JTable table;
    private JScrollPane scrollPane;
    private AbstractTableModel model;
    
    // data for the table
    private Object[][] data = {
        {null, null, null, null},
        {null, null, null, null},
        {null, null, null, null},
        {null, null, null, null}
    };

    // column names for the table
    private String[] columnNames = {
        "Name1", "Name2", "Name3", "Name4"
    };
    
    
    
    public TableOne() {
        // set the Layout for the JPanel
        super(new BorderLayout());
       
        initComponents();
    }
    
    public void initComponents() {
        // Initialize the Abstract Table Model
        model = new MyTableModel();
        
        // Add the model to the JTable
        table = new JTable(model);
        
        // Add the table to the JScrollPane
        scrollPane = new JScrollPane(table);
        
        // Add the scrollPane to the JPanel
        this.add(scrollPane);
    }
    
    // Define the model for the table using AbstractTableModel
    class MyTableModel extends AbstractTableModel{
        
        // Decide the row count according to the data length
        @Override
        public int getRowCount() {
            return data.length;
        }

        // decide the column count according to the columnNames length
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        // put the data values into the table. 
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
        
        // put the columnNames values into the table column names
        @Override
        public String getColumnName(int col){
            return columnNames[col];
        }
        
        // set if the cells in the table are editable. 
        // In this example, all the cells are editable
        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }
         
        // this is for data change. 
        @Override
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }

        /* 
         * JTable uses this method to determine the default renderer/  
         * editor for each cell.  If we didn't implement this method,  
         * then the last column would contain text ("true"/"false"),     
         * rather than a check box.  (From oracle JTable tutorial)
        */
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

    }
    
    /**      
     * Create the GUI and show it.  
     * For thread safety,     
     * this method should be invoked from the     
     * event-dispatching thread.    
     * (from Oracle table tutorial)
     */
    private static void createAndShowGUI() {     
        //Create and set up the window.      
        JFrame frame = new JFrame("TableRenderDemo");    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        
        //Create and set up the content pane.        
        TableOne newContentPane = new TableOne();      
        newContentPane.setOpaque(true); //content panes must be opaque    
        frame.setContentPane(newContentPane);         
        
        //Display the window.    
        frame.pack();      
        frame.setVisible(true);    
    } 
    
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:       
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


for more information about AbstractTableModel,  check
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Thursday, June 13, 2013

Short commnet about MigLayout

Wow 

The guy who made MigLayout is a genius.
It is so easy to use, extremely flexible, and many more!
I was using BorderLayout and Grid Layout to build my interface, and was having hard time. But once I've changed the layout to MigLayout,

BOOM!

No more headaches!

I wish there were someone around who could tell me these kind of information..

Wednesday, June 12, 2013

How to share a variable between classes

In this post, I will explain how to share a variable between classes.

first, you need a seperate class that contains variables you want to share.
I will name this class "DataContainer"

package test_var;

/**
 *
 * @author Lee
 */
public class DataContainer {
    
    private int[] lvl = {1, 2, 3};

    /**
     * @return the lvl
     */
    public int[] getLvl() {
        return lvl;
    }

    /**
     * @param lvl the lvl to set
     */
    public void setLvl(int[] lvl) {
        this.lvl = lvl;
    }
    
    // for chaning lvl value one by one
    public void setLvl(int index, int value) {
        this.lvl[index] = value;
    }

}



Now, lets make two classes that shares the data from DataContainer.
I will name the classes "ClassOne" and "ClassTwo."

Here is the ClassOne
package test_var;

/**
 *
 * @author Lee
 */
public class ClassOne {
    
    public ClassOne(DataContainer data) {
        
        // First, display the original data in the DataContainer
        for(int i = 0; i < data.getLvl().length; i++) {
            System.out.println("Class One Lvl display :" + data.getLvl()[i]);
        }
        
        // Second, change the data in the DataContainer.
        for(int i=0; i < data.getLvl().length; i++) {
            data.setLvl(i, data.getLvl()[i] + 10);
        }
    }
}

And this is ClassTwo
package test_var;

/**
 *
 * @author Lee
 */
public class ClassTwo {
    
    public ClassTwo (DataContainer data) {
        // First, display the original data in the DataContainer
        for(int i = 0; i < data.getLvl().length; i++) {
            System.out.println("Class Two Lvl display :" + data.getLvl()[i]);
        }
        
        // Second, change the data in the DataContainer.
        for(int i=0; i < data.getLvl().length; i++) {
            data.setLvl(i, data.getLvl()[i] + 20);
        }
        
        // then print it
        for(int i = 0; i < data.getLvl().length; i++) {
            System.out.println("Class Two Lvl display :" + data.getLvl()[i]);
        }
    }
    
}        

Brief explanaion of the two Classes

ClassOne gets the origianl data from DataContainer and displays it.
Then it adds 10 to the original data.

ClassTwo gets the data and displays it.
Then it adds 20 to the original data, then displays it.

Here is the main method.

package test_var;

/**
 *
 * @author Lee
 */
public class Display {
    public static void main(String[] args) {
        
        // call the original lvl data = {1, 2, 3}
        DataContainer container = new DataContainer();
        
        // print original lvl data and adds 10 to each of the data
        ClassOne classOne = new ClassOne(container);
        
        // get the changed lvl data and print it. 
        // Then adds 20 to the value and print
        ClassTwo classTwo = new ClassTwo(container);
    }
}

In the main method, ClassOne gets the original data, and modifies it.
Then the ClassTwo get the modified version of data, and changes it again.

Here is the output of the main method.
Class One Lvl display :1
Class One Lvl display :2
Class One Lvl display :3
Class Two Lvl display :11
Class Two Lvl display :12
Class Two Lvl display :13
Class Two Lvl display :31
Class Two Lvl display :32
Class Two Lvl display :33

as you can see, ClassTwo prints 11, 12, 13 since it gets data from ClassOne, then the data becomes 31, 32, 33 after ClassTwo modifies it

Sunday, June 9, 2013

Java JTable using NetBeans GUI builder 3

Topic

How to manipulate the source code of the GUI builder 
(making Check box column)


-----------------------------------------------------------------------------------------
edit
-----------------------------------------------------------------------------------------
I found a  better way to make a JTable then the method I used in this post.
I could just code a table directly and drag and drop it on JFrame form.
So, I guess the infomation on this post is useless?
=====================================================


In this post, I will make a table from this 


to this 

by manipulating the source code, not by the GUI builder



First, lets take a look at the source code of the original table.

public class jtbl_test extends javax.swing.JPanel {

    /**
     * Creates new form jtbl_test
     */
    public jtbl_test() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }//                         
    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}


here, you cannot modify the initComponents() part directly.
Also, it uses .setModel method in the not modifiable area with
the table data and header in it.

So to make it easy to code, I've changed the code as follows



First, you need to set up the model to get rid of this part.
      jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        


at the very last part of the source code where you can modify, add these


 // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
    
    
    /* this part defines the data and header of the table */
    private Object[][] data = {
        {"Singed", 2, false},
        {"Ashe", 3, true},
        {"Riven", 3, false},
        {"Vladimir", 2, true} 
    };
    
    private String[] columnNames = {"Name", "Level", "Vegetarian"};
    
    /* this part initializes the model of the table */
    private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
        @Override
        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };


Now, we have the DefaultTableModel model to replace the
jTable1.setModel(... part.

to do that, go back to design tab, go to navigator tab, and right click the jTable1.



From there, you choose Table contents ...


At the Table Model tab, choose "Custom Code" and put model in the blank




Now, lets see the result. 
To see the result, we need a JFrame to display. 
Go create JFrame Form as below.




Now, you have a blank JFrame form. 
It is time to add the table on it. 



Left Click and drag&drop the table on the JFrame. 


Then you see the following


Exactly the same as before, right?





The final source code of the table is here


 package jtbl_ex;

import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lee
 */
public class jtbl_test extends javax.swing.JPanel {

    /**
     * Creates new form jtbl_test
     */
    public jtbl_test() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        jTable1.setModel(model);
        jScrollPane1.setViewportView(jTable1);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }//                         
    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
    
    
    /* this part defines the data and header of the table */
    private Object[][] data = {
        {"Singed", 2, false},
        {"Ashe", 3, true},
        {"Riven", 3, false},
        {"Vladimir", 2, true} 
    };
    
    private String[] columnNames = {"Name", "Level", "Vegetarian"};
    
    /* this part initializes the model of the table */
    private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
        @Override
        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };

}


I like this version much more than the last post one,
because it is easy to read, and easy to modify


Please let me know if there is better way to do this.

So with this and the Oracle How to JTable tutorial,
I could easily create some more interesting tables.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

end of JTable study notes

Java JTable using NetBeans GUI builder 2


Topic. 
How to create a table with check box. 


In the last post, I covered how to create a basic JTable using netbeans GUI builder.
The problem of using only GUI builder is that it is hard to change the contents as I want.
So netbeans allows users to change the source code, but I find it hard to use.

I think making table using netbeans GUI builder is somewhat inefficient,
but I cant give up using the builder since builder other components such as
buttons and combo box too convenient.

So in this post, I will cover how to create a modified table using the netbeans GUI builder.





Last post, I've created a simple JTable as below




now, I want to change the header as

Name | Level | Vegetarian 

with Vegetarian column as check box.

This can be done very easily as follows.



First, right click the jTable1 in the navigator tab, and choose Table contents. 


Then the following window pops up. 


from there, you can easily change the header name and data of the table. 

You can get the check box in a column by changing the Type of the column 
from object to boolean



This is very straight forward, so I omit the explanation


so now I have the following table. 



now, lets check the source code of this table.
You can check the source code by clicking here





As you can see, most of the code has gray background.  The gray background means
you cannot change the code directly. This makes coding very uneasy to me.
To code into that gray background, you have to do this.

First, go back to design tab (click the Design button right next to the Source button)
Then, right click the jTable1 object in the navigator tab as before, and go to properties.


From there you go to code tab, 



And there, you can code into the gray area.  Play with it and you will see 
which part directs what part in the gray area. 







At the next post, I will do the exact same task by manual coding.








Java JTable using NetBeans GUI builder

This post explains how to create JTable with netbeans GUI builder.
Reading Oracle JTable tutorial will help a lot.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html


CAUTION!
I'm self-taught programmer, so the infomation in this blog may not right.
It would be great if someone tell me where Im wrong.


1. first start up the netbean and create a new project.  Then create new JPanel form file



2. Then you get the below result. Check the right side of netbeans, and you see palette 
and properties.  click those. 




3. From properties tab, you can check the properties of the selected componet.  From Palette tab, you can check various components you can use




4. I want my table to fully fill JPanel, 
so choose Border Layout for the JPanel we've created above



5. now add Scroll Pane to the JPanel. 
Scroll Pane is added automatically when putting JTable, 
but I just add it manually.
This will allow my table to have scroll bar when the displaying window is too
small to fully display the table.
You can check the Scroll Pane is added at the navigator tap at the 
low left corner of the netbeans 




6. Click the Scroll pane and drag&drop it on the JPanel. 




7. Now time to add JTable. Click the Table and drag&drop on the JPanel. 





8. Now we have a simple JTable. as below



9. you can change the number of rows and columns and data of the table by 
right clicking the table name on the left below side.  
You can see the jTable1 object is highlighted as blue in the above screen shot. 
Those process are fairly simple and straight forward, so I omit it. 



At the next post, I will explain how to manipulate the source code of the table  

Saturday, June 8, 2013

// Comment
public class Testing {
public Testing() {
}
 
public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}
hello

this is for testing purpose

Thursday, May 9, 2013

C, Writing Large Programs

  This post is summary of Chapter 15 Writing Large Programs from "C Programming, A mordern approach" by K. N. King

15.2 Header Files
    1. What is Header file?
 ->  In computer programming, a header file is a file that allows programmers to separate certain elements of a program's source code into reusable files. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers.  <http://en.wikipedia.org/wiki/Header_file
    2.  How do we call header files into other source files?
-> use #include 
-> header files have .h extension
    3. Two primary forms of the #include directive
-> #include <filename>    :   this is used for header files that belongs C's own library. Search the directory in which system header files reside
-> #include "filename"     :   this is used for all other header files including any that we write. Search the current directory, then search the directory in which system header files reside
    4. Sharing Macro Definitions and Type Definitions

example of sharing macro definitions and type definitions
          In this way, we can avoid repeating the same macro and type definitions.


    5. Sharing Function Prototypes
 -> Assume there is a source file containing many functions.  We want to call the functions into the other source file.  To avoid any possble errors, we need function prototypes.  The below illustrates how it is done.
-> To share a function, we put its definition in one source file, then put declarations in other files that need to call the function.  
Example of sharing Function Prototypes


    6. Sharing Variable Declarations
-> int i;                    /* declares i and defines it as well*/
-> extern int i;         /* declares i without defining it */
-> extern informs the compiler that i is defined elsewhere in the program.



    7.  Nested Includes
-> Assume that we have two functions that returns only 0 and 1, in other words, true and false.
-> I will use the previous example.  At the 5. Sharing Function prototypes, we had is_empty and is_full function.  Those two only returns 0 and 1.  So change declaring those at stack.h as
int is_empty(void)  => Bool is_empty(void) 
int is_full(void)      => Bool is_full(void)
  
-> to do this, we need to include the boolean.h file in the stack.h, so it becomes

    8. Protecting Header Files
-> If a source file includes the same header file twice, compilation errors may result. This problem is common when header files include other header files.  Consider the following diagram.
-> As you can see, when prog.c is compiled, file3.h will be compiled twice.
-> To prevent this happening, we protect a header file by enclosing the contents of the file in an #ifndef and #endif pair. Below is the example of protection of boolean.h file.
-> so when the boolean.h file is called twice, preprocessor checks if BOOLEAN_H is defined. And it defines BOOLEAN_H only if it hasn't been defined.


Tuesday, May 7, 2013

How I ended up with my programming job


  I'm 29 years old Korean male living in Tokyo, Japan.



  I've finished my high school education in South Korea, then served military for almost 3 years. After I got out of military, I moved to the U.S., and got bachelors degree in applied math. Since I served military for almost 3 years, and spent 5 years in the university, I was already 28 when I graduated the University.  And more importantly I had no programming knowledge and experience except 1 semester of R language (R is programming language used in statistics world).

  At that time, I was getting tired of being in the U.S. and wanted to see other countries.  And working in Japan seems very attractive to me. So I applied to the company I'm working at now, and got a job.

  About my work place, Asahi Glass Co., in short, AGC, is a company making glasses as you can see from its name. It's pretty big company. It has lots of factories all around the world. And since the company is making glasses, I was expecting doing some kind of factory line management or something similar because I didn't have any practical skills other than some basic math knowledge like set theory or probability.  Really, what can you do with the pure theoretical knowledge? However, not like my expectation, the company gave me a programming job. Um, maybe it was my fault that I didn't mention I had no programming experience?

  One funny thing about getting a job in Japan as a fresh graduate is you will never know what kind of work you are going to do in the company.  At least I and other people who got hired at the same time had no clue what we were going to do in this company.  When the company finally told me that I would be a programmer developing a heat transfer simulation software using Java, I asked them back,
  "Um.. excuse me, but what's heat transfer simulation and what is Java?"

  So basically, to develop the physics simulation software, I had to know heat transfer, fluid dynamics, and Java. And as I mentioned, I'm math major without any programming knowledge.  Also, I didn't really enjoy physics, so I didn't take any physics class (They are not required for Math majors).  My school is pretty famous in Japan, so my boss had very high expectation on me.  And when he found out that I'm virtually useless, he got really really disappointed.  He wanted me to learn all the physics and programming skills in a half year.  However, since I'm not a genius, I failed.  Then he stopped talking to me anymore. So I could have plenty of time spending reading books about programming.

  I've been working in this company about one year.  Now I call myself self-taught programmer.  I read books and Goolge to get knowledge I need.  So far, I've developed one simple heat radiation simulation software using Java and JOGL(JOGL is Java version of OpenGL).  Now, my goal is studying C and CUDA so that I can do some GPGPU.  I'm not sure how far I can go by teaching myself with little help from others.  I don't even know I'm doing it right. But it is fun, so I will keep doing this till I get eventually fired from this company.

  This blog will be my personal diary of what I'm doing at my work, how I feel, and others.