Friday, June 27, 2014

How to execute code in a method/constructor after the execution of the method/constructor is finished

To execute certain code after all the other code in the same method/constructor has been executed, you need to create a new thread  and make the new thread to wait util the parent thread finishes execution.

Following is an example.

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FocusTest extends JFrame {
    JTextField f1 = null;
    JButton b1 = null;

    public FocusTest() {
        getContentPane().setLayout(new GridLayout(2,2));
        JLabel label1 = new JLabel("Input 1: ");
        f1 = new JTextField(15);
        b1 = new JButton("button 1");
     
        add(label1);
        add(f1);
        add(b1);
     
        ArrayList<Component> tp = new ArrayList<Component>();
        tp.add(f1);
        tp.add(b1);
     
        //the following code will not work
        //because the layout of button 1 is not realized
        //b1.requestFocusInWindow();
     
        //request focus on button 1
        //after all the other code in the constructor is executed.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               b1.requestFocusInWindow();
           }
        });
     
        b1.addActionListener(new ButtonListener());
        f1.addFocusListener(new F1FocusListener());
     
        b1.setEnabled(false);
     
        pack();
        setVisible(true);
    }
 
    private class F1FocusListener extends FocusAdapter {
        public void focusGained(FocusEvent e){
            if (e.getSource().equals(f1)){
             
                //because button 1 is disabled
                //the following code will do nothing
                //b1.doClick();
             
                //will programmatically click button 1
                //after all the other code in the method is executed.
                javax.swing.SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        b1.doClick();
                    }
                });
             
                b1.setEnabled(true);
            }
        }
    }
 
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e){
            if (e.getSource() == b1){
                f1.setText("Excellent job!!!!");
            }
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FocusTest();
            }
        }
        );
    }
}

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Set focus to a field in window/frame (2): FocusTraversalPolicy

The FocusTraversalPolicy controls the sequence of fields gaining focus when you tapping through the fields and also the field that has the focus when the window/frame is first constructed/activated/visible.

Following is a sample code.

import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FocusTest extends JFrame {
    JTextField f1 = null;
    JTextField f2 = null;
    JButton b1 = null;
    JButton b2 = null;
    public FocusTest() {
        getContentPane().setLayout(new GridLayout(3,2));
        JLabel label1 = new JLabel("Input 1: ");
        JLabel label2 = new JLabel("Input 2: ");
        f1 = new JTextField(15);
        f2 = new JTextField(20);
        b1 = new JButton("button 1");
        b2 = new JButton("button 2");
     
        add(label1);
        add(f1);
        add(label2);
        add(f2);
        add(b1);
        add(b2);

        b1.addActionListener(new ButtonListener());
        b2.addActionListener(new ButtonListener());
     
        ArrayList<Component> tp = new ArrayList<Component>();
        tp.add(f1);
        tp.add(f2);
        tp.add(b1);
        tp.add(b2);
     
        setFocusTraversalPolicyProvider(true);
        setFocusTraversalPolicy(new MyTraversalPolicy(tp));
     
        pack();
        setVisible(true);
    }
 
    private class MyTraversalPolicy extends FocusTraversalPolicy {
        ArrayList<Component> components = null;
        public MyTraversalPolicy(ArrayList<Component> list){
            this.components = list;
        }
     
        public Component getComponentAfter(Container focusCycleRoot, Component focused){
            int idx = components.indexOf(focused);
            if (idx >= components.size()-1){
                idx = -1;
            }
            return components.get(idx+1);
        }
     
        public Component getComponentBefore(Container c, Component focused){
            int idx = components.indexOf(focused);
            if (idx <= 0){
                idx = components.size();
            }
            return components.get(idx-1);
        }
     
        public Component getDefaultComponent(Container c){
            return f2;
        }
     
        public Component getFirstComponent(Container c){
            return components.get(0);
        }
     
        //Set the field of focus 
        //when the window is first activated/contructed/visible
        public Component getInitialComponent(Window w){
            return f2;
        }
     
        public Component getLastComponent(Container c){
            return components.get(components.size()-1);
        }
    }
 
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e){
            if (e.getSource() == b1){
                f1.setText("button 1 is pressed");
                f2.setText("");
            } else if (e.getSource() == b2){
                f2.setText("button 2 is pressed");
                f1.setText("");
            }
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FocusTest();
            }
        }
        );
    }
}

            Previous <

Reference:

1. Set focus to a field in java swing when a window/JFrame is first activated/constructed (1): requestFocusInWindow

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, June 26, 2014

Set focus to a field in java swing when a window/JFrame is first activated/constructed/visible (1): requestFocusInWindow

To set focus to a field in a java swing user interface, you can use either the requestFocusInWindow method of java.awt.Component or the java.awt.FocusTraversalPolicy and the setFocusTraversalPolicy method of java.awt.Component.

The requestFocusInWindow method works only after the layout of the component that is going to gain focus in the window/frame is complete, which means it works only after the pack method is called. This can be achieved by either putting the requestFocusInWindow method after the pack method or using the invokeLater method of SwingUtilities to call the requestFocusInWindow method.

Following is a sample code.

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FocusTest extends JFrame {
    public FocusTest() {
        getContentPane().setLayout(new GridLayout(2,2));
        JLabel label1 = new JLabel("Input 1: ");
        JLabel label2 = new JLabel("Input 2: ");
        JTextField f1 = new JTextField(15);
        JTextField f2 = new JTextField(20);
     
        add(label1);
        add(f1);
        add(label2);
        add(f2);
     
        //the following will not work
         //f2.requestFocusInWindow();

        //the following will work
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               f2.requestFocusInWindow();
           }
        });

        pack();
     
        //the following will work
        //f2.requestFocusInWindow();
     
        setVisible(true);
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FocusTest();
            }
        }
        );
    }
}

                               > Next

Reference:

1. Set focus to a field in window/frame (2): FocusTraversalPolicy

--------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, June 16, 2014

DynamicReports: Currency columns, Currency type, Money type

There are two ways to make a currency column to automatically display the currency symbol. One is to create a new currency type and set the column's data type to that currency type. The other way is to define a  pattern of how you would like the column to display the data. The advantage of doing it in these ways instead of converting the data to a string and attach the money symbol in front of it is that it not only shows that the column is holding an amount of money, what type of money it is and you can at the same time use the column to do mathematical calculations.

import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.BigDecimalType;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.builder.style.Styles;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.constant.PageType;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

public class DynamicReportsTest {

    public DynamicReportsTest() {
        build();
    }

    public void build() {
        JasperReportBuilder report = DynamicReports.report();
        report.setPageFormat(PageType.LETTER);
//        report.setPageFormat(PageType.A4, PageOrientation.PORTRAIT);

        //Create the Currency Object
        CurrencyType currencyType = new CurrencyType();
     
       //Set the currency type
        TextColumnBuilder<BigDecimal> priceColumn = Columns.column("Price", "price", currencyType);
        TextColumnBuilder<Integer> quantityOrderedColumn = Columns.column("Quantity Ordered", "quantityOrdered", DataTypes.integerType());
        TextColumnBuilder<BigDecimal> totalPay = priceColumn.multiply(quantityOrderedColumn)
                //Set the currency pattern
                .setTitle("Amount Paid")
                .setPattern(currencyType.getPattern());
  //            .setPattern("$#,###,###.00");
        report.columns(Columns.columnRowNumberColumn("Item"),
                Columns.column("Name", "name", DataTypes.stringType()),
                priceColumn,
                quantityOrderedColumn,
                totalPay
        );

        StyleBuilder bold = Styles.style().bold();
        StyleBuilder centeredBold = Styles.style(bold)
                .setHorizontalAlignment(HorizontalAlignment.CENTER);
        StyleBuilder columnStyle = Styles.style(centeredBold)
                .setBackgroundColor(Color.LIGHT_GRAY)
                .setBorder(Styles.pen1Point());

        report.setColumnTitleStyle(columnStyle);
        report.setColumnStyle(Styles.style().setHorizontalAlignment(HorizontalAlignment.CENTER));
        report.highlightDetailEvenRows();
     
        report.title(Components.text("Test Report")
                .setStyle(centeredBold));
        report.title(Components.text("Detailed Report")
                .setStyle(centeredBold));
     
        report.pageFooter(Components.horizontalFlowList().add(Components.text("Page "))
                .add(Components.pageNumber())
                .setStyle(bold));
     
        report.setDataSource(createDataSource());
     
        try {
            report.show();
//            java.io.File file = new java.io.File("<your file path and name>.pdf");
            java.io.File file = new java.io.File("<your file path and name>.txt");
//            report.toPdf(new FileOutputStream(file));
            report.toText(new FileOutputStream(file));
        }catch(DRException e){
            e.printStackTrace();
        } catch (FileNotFoundException fe){
            fe.printStackTrace();
        }
    }
 
    private class CurrencyType extends BigDecimalType {
        @Override
        public String getPattern() {
            if (usaMoney) {
                      return "$ #,###.00";
            } else if (ukMoney){
                      return "£ #,###.00";
             } else if (euroMoney) {
                       return " #,###.00";
             }
             return "¥ #,###.00";  
        }
    }
 
    private JRDataSource createDataSource() {
        DRDataSource dataSource = new DRDataSource("name", "price", "quantityOrdered");
        dataSource.add("Apple", new BigDecimal(1.29), 120);
        dataSource.add("Apple", new BigDecimal(1.69), 150);
        dataSource.add("Orange", new BigDecimal(0.99), 130);
        dataSource.add("Orange", new BigDecimal(0.96), 100);
        dataSource.add("Mange", new BigDecimal(2.99), 300);
        return dataSource;
    }
 
    public static void main(String[] args){
        new DynamicReportsTest();
    }
}
       
------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, June 6, 2014

NetBeans The type of [method call] is erroneous

While you are working with your code, the NetBeans IDE sometimes unexpectedly shows an error sign. When hovering the cursor over the place underlined with a curly red line, the message says that the type of <mehtod> is erroneous.

This type of error sign occurs in the following situations
1. When a final method in the super class is called from a subclass.
         public class SuperPowerful {
                   public final String getTheString() {
                             return "Super class final method is called";
                   }
         }

         public class SubPowerful  extends SuperPowerful {
                   public void printString() {
                             //The error sign shows on this line of code
                             String str = getTheString(); 
                             System.out.printlin(str);
                   }
          }

2. When creating a class instance using a return type of an interface that is not directly implemented by this class, but is implemented by its super class.
          public interface SunRisingInterface {
                    public void sunIsRising();
          }

          public class GeneralSunRise implements SunRisingInterface {
                   public void sunIsRising() {
                             System.out.println("get ready to watch sun rising!!!");
                   }
          }

          public class SummerSunRise extends GeneralSunRise {
                     public static void main(String [] args) {
                               //The error sign shows on this line of code
                               SunRisingInterface sri = new SummerSunRise();
                               sri.sunIsRising();
                     }
          }

However the code compiles and runs just fine. You can either ignore the error sign, but if your feel uncomfortable to work while there is an error sign you may fix the problem as stated below.

To fix this problem

A. Remove and add back the jar containing the super class to the project library/path if the super class and sub class are contained in two different projects. Let's say that the super class is in project A and the sub class is in project B.
  1. Right-click on project B and select "Porperties".
  2. Click "Libraries" on the left under Categories.
  3. Select the library or the jar of project A in the right pane and click the "Remove" button to remove it.
  4. Click "OK" to close the window.
  5. Restart NetBeans.
  6. Repeat steps 1 and 2.
  7. Click the "Add Library" or "Add JAR/Folder" button to add the library or the jar of project A back to project B.
B. Remove the final  keyword from the method in the super class.

C. Change public class SummerSunRise extends GeneralSunRise to public class SummerSunRise extends GeneralSunRise implements SunRisingInterface.
       
---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, June 5, 2014

java.sql.SQLException: Fail to convert to internal representation



Stack Trace:
java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.CharCommonAccessor.getLong(CharCommonAccessor.java:239)
at oracle.jdbc.driver.OracleResultSetImpl.getLong(OracleResultSetImpl.java:558)

The above exception occurs when a field data is retrieved from the ResultSet using a wrong data type that does not match the data type in the database, for example retrieving a varchar field in the database table from the ResultSet using getInt() or retrieving a integer field with getLong(), etc.

If you are using a counter such as

          int counter = 1;
          while (rs.next()) {
                    rs.getString(counter++);
                    rs.getInt(counter++);

                    ...........
          }

Check your code to make sure that the order of the fields in the select clause of your sql statement is in the same order as you retrieving the data from the result set (though this is not required for processing a result set). The data type of the get method has to match the data type of the field in the database.

-----------------------------------------------------------------------------------------------------------


                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, June 2, 2014

DynamicReports: Setting column width and alignment

JasperReportBuilder report = DynamicReports.report();

report.setPageFormat(PageType.LETTER, PageOrientation.LANDSCAPE);
report.setPrintOrder(Orientation.VERTICAL);

StyleBuilder titleStyle = Styles.style().bold().setHorizontalAlignment(HorizontalAlignment.CENTER);
report.title(Components.text("Test Report")
                .setStyle(titleStyle));

report.columns(Columns.column("column 1", "col1", DataTypes.stringType())
                         //set the column width to 10 columns
                         .setFixedColumnWidth(10)

                         //set the column width to 20 pixels
                         //.setFixedWidth(20)
                         //.setMinWidth(15)
                         //.setMinColumns(8)

                        //set the column alignment
                        .setStyle(Styles.style().setHorizontalAlignment(HorizontalAlignment.LEFT)
                                                          .setVerticalAlignment(VerticalAlignment.TOP)
                        //.setStyle(Styles.style().setHorizontalAlignment(HorizontalAlignment.RIGHT)
                                                           .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        //.setStyle(Styles.style().setHorizontalAlignment(HorizontalAlignment.CENTER)
                                                            .setVerticalAlignment(VerticalAlignment.BOTTOM)
);

report.setDataSource(<your data source>);

report.show(false);
       
----------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.