miércoles, 30 mayo 2007

Dynamic icons for your JComponents // Create an icon JButton with dynamic icons.

Internet offers many opportunities and possibilities for developers with imagination. Today, most search engines and specialized sites count with API's to access their data from other software, sites, devices...

Today I'm going to show you a dirty example of how this apis can benefit your program. In less of ten lines of code (someone intelligent would have done it in less) I will add an Icon to a jButton with an image stored in the net.

To do this I will use yahoo's Image Search API, documentation can be found here. For demonstration purposes I will use the YahooDemo applicationId, you will need to create one if you intend to use this api in your programs.

In brief, what the program does is decode what the browser gets when it reads an url constructed with the api guidelines. The response is an XML inputStream where you can get the url of a thumbnailed image which you can then pass to the JButton.

try {
            URL pepe = new URL("http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=client%20icon&results=1&format=gif");
            BufferedReader br = new BufferedReader(new InputStreamReader(pepe.openStream()));
            String text ="";
            String line = null;
            while((line = br.readLine()) != null){
                text += line+"\n";
            }
            text = text.substring(text.indexOf("<Thumbnail>"));
            text = text.substring(text.indexOf("<Url>")+5, text.indexOf("</Url>"));
            BufferedImage img = ImageIO.read(new URL(text));
            jButton1.setIcon(
                    new ImageIcon(img));
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

When you run this code this is what you get:
Customer

As you can see the program is quite simple. In the first part, you generate an URL with the desired variables. In this case, we want a customer icon in a gif format. You can refer to the api guide to customize your URL. In second place, we get the contents of the URL and parse it to get the location of the thumbnail image. Finally we get the thumbnailed image using ImageIO.

You can download a running version of the code here.

Technorati Tags:

Posted by admin at 9:16 AM in Java

miércoles, 23 mayo 2007

JTable, detecting selection changes // ListSelectionListener /*Selection Changed Event*/

When working with tables, it may be useful to detect selection changes. If for example, you need to sum the values of a specified column in a selection range, this method will be most essential.

If you explore the available methods to add listeners to a JTable, you will notice there's no such thing as a selectionListener. This is because the JTable has its own selection model, where you can add the listener.

The following code illustrates the way to go to add a selection listener:

JTable jtable = new JTable();
jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
        /*TODO: Add whatever you need to do when the selection changes */
    }
});

Technorati Tags:

Posted by admin at 5:25 PM in Java

lunes, 21 mayo 2007

SimpleDateFormat to check user date input // parsing String to dates in java

When developing user interfaces for management software you usually need to check what the user inputs in order to store the values in a database or a file. Java offers different alternative to parse String (normally the way user inputs values to the system) to other data types.

The class SimpleDateFormat from the package java.text offers a simple method to do this. You just have to call parse(String youDate) in order to get a java.util.Date.

Following you can find some code which explains this method and some of its particularities:

/* We create the SimpleDateFormat object with the desired patter */
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        /* This is very important. If you need strict parsing, (i.e. January
         * will only have 31 days you must set this to false.
         * If you don't do this when you parse "32/01/2007" the date you'll
         * you'll get really be 01/02/2007*/
        sdf.setLenient(false);
        try {
            System.out.println(sdf.parse("25/12/2022"));
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        /* This first parse offers no problem, when run you will get
         * Sun Dec 25 00:00:00 CET 2022
         * in the console*/

        try {
            System.out.println(sdf.parse("34/15/2002"));
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        /* In this case, the date is wrong thus we will get the correspondant 
         *  exception */
        try {
            System.out.println(sdf.parse("28/02/202"));
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        /* This time we will not get an exception, but in some cases we would like
         to get the exception, because this date although valid, has an uncommon
         length and may be due to an input error.*/

    /*To solve the above proble, we could create the following function:*/
    public Date parseDate(String date) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        if(date.length() != 10){
            throw new ParseException("Date with wrong length: "+date, 0);
        }
        return sdf.parse(date);
    }

Technorati Tags:

Posted by admin at 11:09 AM in Java

lunes, 7 mayo 2007

Numbers to Strings with custom symbols // DecimalFormat - DecimalFormatSymbols

When printing reports or casting Strings to Numbers, its very useful to use the DecimalFormat class found in java.text. This class is pretty straightforward and easy to use, but some problems may be found when your work with this class in computers from other countries. Internationalization will cause your program to behave in a way you may not expect in some cases.

If you use these class to parse a number to a String, you may find that when a user enters a number in a french computer you will be getting a ParseException, because the computer is expecting different symbols. Here is where the DecimalFormatSymbols class becomes very useful.

With the following code I'll show you how easy is to change the symbols and make them independent of different Locales.


/* We create our formatter using a DecimalFormat Instance.
         * We use these method instead of (new DecimalFormat(String pattern))
         * because in computers with different locales, we may have problems when
         * setting the pattern. This way we assure we always work with the same variables.
         **/
        DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance(Locale.ENGLISH);
        /* We set the typical pattern with thousand separator and two decimal places */
        format.applyPattern("#,##0.00");
        /* Now we do the work to change the formatting symbols 
         * We will set the typical spanish symbols*/
        DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
        dfs.setDecimalSeparator(',');
        dfs.setGroupingSeparator('.');
        format.setDecimalFormatSymbols(dfs);
        /* We do two simple tests */
        System.out.println(format.format(1000234234.56772345d));
        try {
            System.out.println(format.parse("1.258.254,25"));
        } catch (ParseException ex) {
            ex.printStackTrace();
        }

Technorati Tags:

Posted by admin at 6:49 AM in Java

Google
 
« May »
SunMonTueWedThuFriSat
  12345
6789101112
13141516171819
20212223242526
2728293031