miércoles, 30 mayo 2007

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

« JTable, detecting selection changes // ListSelectionListener /*Selection Changed Event*/ | Main | Detecting Tab Key Pressed Event in JTextField 's // Event.VK_TAB KeyPressed »

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

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 

SCode

Please enter the code as seen in the image above to post your comment.

 
 

Live Comment Preview:

 
Google
 
« May »
SunMonTueWedThuFriSat
  12345
6789101112
13141516171819
20212223242526
2728293031