Search
Relevant Links
Top 10 Articles
Jetty - Java Developers's Guide To Latest Web Server Technology
Jetty, an Open source application server from Java has been the talk of the Developers community these days
Jetty - Java Developers's Guide To Latest Web Server Technology
Advantage And Disadvantages Of String Implementation In JAVA
Advantages of the String implementation in JAVA
Advantage And Disadvantages Of String Implementation In JAVA
Hibernate Vs JDBC Performance
The Hibernate advantage over JDBC
Hibernate Vs JDBC Performance
Choosing Java Vs .Net For Web Development
Choosing Java Vs .Net For Web Development
Choosing Java Vs .Net For Web Development
How To Call Java Applet Functions From Javascript
How to Call Java Applet Functions From Javascript
How To Call Java Applet Functions From Javascript
Java 2 Platform Enterprise Edition (J2EE) Three-Tier Model
Enterprise edition of J2EE is used for developing modular enterprise request.
Java 2 Platform Enterprise Edition (J2EE) Three-Tier Model
What Is Java Virtual Machine
What is java virtual machine?
What Is Java Virtual Machine
How Does Java Handle Overriding
Overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++
How Does Java Handle Overriding
Java Interface Overview
Interface: Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy
Java Interface Overview
Enterprise Java Bean Application Development With A Three-Tier Architecture
Enterprise java beans is basically a server side component architecture for developing modular enterprise applications based on the java platform
Enterprise Java Bean Application Development With A Three-Tier Architecture
Use Of Hibernate With Java Persistence API
Hibernate has become immensely popular amongst the developer community as it is a free, powerful, high performance open source object
Use Of Hibernate With Java Persistence API
Java Embedded Applications
Java, or J2ME is a format for applications for mobile and PDAs. It provides software that can been added to mobile phones
Java Embedded Applications
How Does Java Handle Overriding?
Overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++. In C++, the concept of overriding functions are handled by Virtual Table, VTable
How Does Java Handle Overriding?
Work With Teradata Using Java
Teradata is one of the leading vendor in data analytics and data warehousing applications and softwares.
Work With Teradata Using Java
Point To Point Video Conferencing Using Java's JMF API
When a face-to-face meeting with someone far away becomes a necessity or a compelling presentation must be given to a remote person,
Point To Point Video Conferencing Using Java's JMF API
Learning Java Programming Coding Language
There are many programming languages available and each of them is suitable for another program or application.
Learning Java Programming Coding Language
Java Hashtable
A collection allows a group of objects to be treated as a single unit.
Java Hashtable
Working With JNDI In A J2SE Application
Java Naming and Directory Interface (JNDI) allows Java objects to be published to a directory service which can be accessed by other Java applications later.
Working With JNDI In A J2SE Application
Java Games - The World Of Excitement Is Readying With Options!
Mobile phones have grown from the pedestal of a mere communication tool and with the aid of some innovative steps plus the technological up-gradation
Java Games - The World Of Excitement Is Readying With Options!
Everything You Need To Know And How To Use Java
Java is an object-oriented programming language developed by Sun Microsystems in the early 1990s
Everything You Need To Know And How To Use Java
Of CGI And Java Scripts
CGI and Java Scripts are both functional with both Netscape and Internet Explorer browsers.
Of CGI And Java Scripts
Free Java Games - Entertain Yourself In Your Leisure Time
Today, you can find cell phones having multifunctional organisational tools
Free Java Games - Entertain Yourself In Your Leisure Time
Ajax Applications Development
AJAX has not only sprouted but has got root hold in developing dynamic web applications,
Ajax Applications Development
Benefits And Pitfalls Of A Java-Based Forex Trading Platform
Many forex brokers today offer a Java-based platform to traders as opposed to the traditional software that needs to be installed on your computer.
Benefits And Pitfalls Of A Java-Based Forex Trading Platform
Point To Point Video Conferencing Using Java's JMF API
When a face-to-face meeting with someone far away becomes a necessity or a compelling presentation must be given to a remote person, video conferencing is always your best choice
Point To Point Video Conferencing Using Java's JMF API
What Is CLASSPATH
A path specifies the name and location of a file on the file system.
What Is CLASSPATH
Javascript Is Not Java
Repeat after me: JavaScript is not Java, JavaScript is not Java. . .
Javascript Is Not Java
Eclipse IDE
Eclipse is an open-source, platform-independent software framework for delivering what the project calls "rich-client applications".
Eclipse IDE
Tomcat Jsp Run Error:Unable To Find A Javac Compiler
I always get this error when I run simple jsp files in my Tomcat 5.0.19/win2000. These jsp files run on other versions of Tomcat on the same PC. Any ideas?
Tomcat Jsp Run Error:Unable To Find A Javac Compiler
Deploying Web Applications To Tomcat
In this article we are going to cover the deployment of web applications using Tomcat.
Deploying Web Applications To Tomcat
Running The Tomcat 4.0 Servlet/JSP Container
Tomcat 4.0, a server that implements the Servlet 2.3 and JSP 1.2 Specifications from Java Software. In order to install and run this container, you must do the following
Running The Tomcat 4.0 Servlet/JSP Container
SOAP Example
In the example below, a GetStockPrice request is sent to a server. The request has a StockName parameter, and a Price parameter will be returned in the response.
SOAP Example
SOAP HTTP Binding
HTTP communicates over TCP/IP. An HTTP client connects to an HTTP server using TCP. After establishing a connection, the client can send an HTTP request message to the server:
SOAP HTTP Binding
SOAP Fault Element
The optional SOAP Fault element is used to hold error and status information for a SOAP message.
SOAP Fault Element
SOAP Body Element
The mandatory SOAP Body element contains the actual SOAP message.
SOAP Body Element
Introduction To SOAP
SOAP is a simple XML based protocol to let applications exchange information over HTTP.
Introduction To SOAP
Where Did Java Come From?
In the late 1970's Bill Joy thought about doing a language that would merge the best features of MESA and C
Where Did Java Come From?
What Is Java?
Java, formerly known as oak, is an object-oriented programming language developed by Sun
What Is Java?
How Do I Format Numbers Like C's Printf()?
Java does not have any built in equivalent to C's printf/sprintf/fprintf family of functions that specify the width and precision of numbers converted into strings.
How Do I Format Numbers Like C's Printf()?
How Do I Play A Sound In An Application?
Java's audio support comes from the AppletContext class and the AudioClip interface. Since applications don't have applet contexts, they have no easy way to play audio clips
How Do I Play A Sound In An Application?
Java Interview Questions
Java Interview Questions for java programmers !
Java Interview Questions
Java Games For Your Cell Phone
Are you one of those people who get tired when standing in queue? Can't stop multitasking no matter what you do
Java Games For Your Cell Phone
Pros And Cons Of JavaScript
Javascript use is very common across the Internet; but just because it is popular, does that mean you should use it for your site
Pros And Cons Of JavaScript
Tag Libraries
JSP 1.1 introduces a method of extending JSP tags, called "tag libraries".
Tag Libraries
Beans And Form Processing
The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean.
Beans And Form Processing
JSP Sessions
If you are programming the site, it is very helpful to be able to associate some data with each visitor. For this purpose, "session"s can be used in JSP
JSP Sessions
JSP Tags
Another important syntax element of JSP are tags. JSP tags do not use <%, but just the < character. A JSP tag is somewhat like an HTML tag.
JSP Tags
JSP Directives
We have been fully qualifying the java.util.Date in the examples in the previous sections. Perhaps you wondered why we don't just import java.util.*;
JSP Directives
Mixing Scriptlets And HTML
We have already seen how to use the "out" variable to generate HTML output from within a scriptlet.
Mixing Scriptlets And HTML
JSP:Scriptlets
JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters
JSP:Scriptlets
Categories
Related Links

 

Java4Programmers.com

Java4Programmers.com This is a high-level informational site for java programmers outside of Sun Microsystems. This is a categorized directory of information sources for Java, including sources, communities, tools, etc.

Java Tutorial

Java Tutorial : Learn Painters In LWUIT 1.1

 

The Painter interface

Painter defnes the fundamental interface for all objects that are meant to draw backgrounds or to render on a glass pane. This interface declares  only one method—public void paint(Graphics g, Rectangle rect)—for drawing inside the bounding rectangle (specifed by rect) of a component. The library provides a class that implements Painter and is used as a default background painter for widgets and containers. This is the BackgroundPainter class that has (you guessed it) just the one method paint, which either paints the background image if one has been assigned or fills in the bounding rectangle of the component with the color set in its style.

When we want to paint a background ourselves, we can write our own class that implements Painter, and set it as the background painter for the relevant component. The DemoPainter MIDlet, discussed in the next section, shows how this is done.

The DemoPainter application

This application creates a combo box and uses a theme to set the style for the various elements that are displayed. When the application is compiled without setting a custom background painter, the combo box looks as shown in the following screenshot:

The MIDlet code has the following statement commented out in the MIDlet. When uncommented, this statement sets an instance of ComboBgPainter as the background painter for the combo box.

combobox.getStyle().setBgPainter(new ComboBgPainter(0x4b338c));

The recompiled application produces the following display showing the new background color:

The class responsible for drawing the background is ComboBgPainter, which implements Painter. The constructor for this class takes the color to be used for background painting as its only parameter. The paint method determines the coordinates of the top-left corner of the rectangle to be painted and its dimensions. The rectangle is then flled using the color that was set through the constructor.

class ComboBgPainter implements Painter
{
private int bgcolor;
public ComboBgPainter(int bgcolor)
{
this.bgcolor = bgcolor;
}
public void paint(Graphics g, Rectangle rect)
{
g.setColor(bgcolor);
int x = rect.getX();
int y = rect.getY();
int wd = rect.getSize().getWidth();
int ht = rect.getSize().getHeight();
g.fillRect(x, y, wd, ht);
}
}

Drawing a multi-layered background

In actual practice, there is hardly any point in using a custom painter just to paint a background color, because the setBgColor method of Style will usually do the job. Themes too can be used for setting background colors. However, painters are very useful when intricate background patterns need to be drawn, and especially if multiple layers are involved. PainterChain, described in the next section, is a class designed for handling such requirements.

The PainterChain class

It is possible to use more than one painter to render different layers of a background. Such a set of painters can be chained together through the PainterChain class. The only constructor of this class has the form public PainterChain(Painter[] chain) where the parameter chain is an array of painters. The contents of chain will be called sequentially during the painting of a background, starting from the element at index 0 to the last one.

There are two methods of the PainterChain class that provide support for adding painters to the array underlying the chain. A new painter can be added either to the top (the prependPainter method) or at the end (the addPainter method) of the array. The array itself can be accessed through the getChain method.

PainterChain implements Painter so that the setBgPainter method can be used to set a PainterChain as well as a lone painter, which means the paint method also is present here. The function of paint in PainterChain is to call the paint methods of the painter array elements one by one starting at index 0.

The DemoPainterChain application that comes up next shows how a chain of painters can be used to draw the multiple layers of a background.


The DemoPainterChain application

The DemoPainterChain example uses alphaList to show a painter chain in action. After organizing the form and the list, we set up a painter array to hold the three painters that we shall deploy.

Painter[] bgPainters = new Painter[3];

Once we have the array, we create three painters and load them into the array. The frst (lowest) painter, which will fll the bounding rectangle for the list with a designated color, goes in at index 0. The next (middle) layer, at index 1, will draw an image at the center of the list. Finally, the topmost layer for writing a text a little below the center line of the list is inserted at index 2.


bgPainters[0] = new Eraser(0x334026);
try
{
bgPainters[1] = new ImagePainter(Image.createImage(
"/a.png"));
}
catch(java.io.IOException ioe)
{
}
bgPainters[2] = new TextPainter("This is third layer");

Now we are ready to instantiate a PainterChain object, and install it as a background painter for the list.

PainterChain bgChain = new PainterChain(bgPainters);
alphaList.getStyle().setBgPainter(bgChain);

The list itself will be drawn on top of these three layers, and the background layers will be visible only because the list is translucent as determined by the transparencyvalue 100, set by the AlphaListRenderer instance used to render alphaList. The list now looks as shown in the following screenshot:

A close inspection of the screenshot that we have just seen will show that the layers have indeed been drawn in the same sequence as we had intended. The three painters are very similar in structure to the ComboBgPainter class we came across in the previous example. The Eraser class here is virtually identical to ComboBgPainter. The other two classes work in the same way, except for the fact that TextPainter draws a line of text, while ImagePainter draws an image.

class TextPainter implements Painter
{
private String text;
TextPainter(String text)
{
//set the text to be written
this.text = text;
}
public void paint(Graphics g, Rectangle rect)
{
//get the dimension
//of background
int wd = rect.getSize().getWidth();
int ht = rect.getSize().getHeight();
//create and set font for text
Font textFont = Font.createSystemFont(
Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);
g.setFont(textFont);
//set text color
g.setColor(0x0000aa);
//position text slightly below centerline
int textX = wd/2 - textFont.stringWidth(text)/2;
int textY = ht/2 - textFont.getHeight()/2 + 3;
//write text
g.drawString(text, textX, textY);
}
}

class ImagePainter implements Painter
{
private Image bImage;
ImagePainter(Image bImage)
{
//set the image to be drawn
this.bImage = bImage;
}
public void paint(Graphics g, Rectangle rect)
{
//get the dimensions
//of background
int wd = rect.getSize().getWidth();
int ht = rect.getSize().getHeight();
//position image at center
int imageX = wd/2 - bImage.getWidth()/2;
int imageY = ht/2 - bImage.getHeight()/2;
//draw image
g.drawImage(bImage, imageX, imageY);
}
}

When an image is used on the background of a form, we have seen that it is scaled to occupy the entire form real estate. But if the same image is used as an icon for a label, then it is drawn in its actual size. This task of scaling the image for backgrounds is taken care of by BackgroundPainter, which is used as the default bgPainter.



LWUIT 1.1 for Java ME Developers
 
LWUIT 1.1 for Java ME Developers Create great user interfaces for mobile devices
  • Make your applications stand out with dazzling graphics that look and behave the same on different mobile devices
  • Log information on the runtime behavior of your program
  • Write applications with attractive visual effects like transitions and animations
  • Use localization so that your applications can adapt to different languages and locales
 http://www.packtpub.com/lwuit-1-1-for-java-me-developers/book


The scaleImage attribute of Style determines whether the background image of a component should be scaled (scaleImage == true) or tiled (scaleImage == false), and its default value is true. When required, scaleImage can be set to any value by calling the setScaleImage method of Style. Before drawing the background image, the default background painter calls the isScaleImage method of Style. If the returned value is true and the dimensions of the background image are not the same as those of the background (specified by the parameter rect of paint method), then the image is scaled to the same size as that of the rectangle to be drawn into. This image is then set as the background image so that the scaling does not have to be done over and over again.

In our case, we need not check the scaleImage attribute, as we have already decided that scaling is required. So all we need to do is compare the dimensions of the image with those of the background we are drawing on and scale it if required. Then we save the scaled version so that it will not be necessary to scale it the next time this method is called. In order to see the effect of scaling, we replace the paint method of the ImagePainter class with the following version. The highlighted code does the scaling.

public void paint(Graphics g, Rectangle rect)
{
//get the dimensions and position
//of background
int imageX = rect.getX();
int imageY = rect.getY();
int wd = rect.getSize().getWidth();
int ht = rect.getSize().getHeight();
//check if image dimension different
//from component background dimension
if (bImage.getWidth() != wd || bImage.getHeight() != ht)
{
//scale image and save
bImage = bImage.scaled(wd, ht);
}
//draw image
g.drawImage(bImage, imageX, imageY);
}

The new paint method creates the following list. Note the change in background color, which is now the same as that of the image, as it has been scaled up to cover the original background.

Using a glass pane

A glass pane is indeed like a fully transparent and distortion free glass sheet placed over a form. We can draw whatever we want on the pane, and only the part of the form under that pattern will be obscured. The rest of the form will be visible. Also, the pattern drawn on the glass pane will not be affected by any transition, animation, or change of any kind that may take place on the form below.

In the world of LWUIT, a glass pane is also a painter. However, unlike the painters we have used so far, a glass pane can only be used with a form. Let us see, with the help of the DemoGlassPane example, how to install a glass pane.

The DemoGlassPane application

For this application as well, the basic building block is alphaList on which we shall place a glass pane with text written on it. The action required is very simple as the following snippet shows:

try
{
demoForm.setGlassPane(new ImagePainter(Image.createImage(
"/text.png")));
}
catch(java.io.IOException ioe)
{
}

We just created an instance of our old friend ImagePainter and installed it as a glass pane on demoForm. The statement invoked for installing the glass pane is one of the two that can be used. We could have used the static method of PrinterChain shown below to get the same result.

PainterChain.installGlassPane(demoForm, new ImagePainter(Image.
createImage("/text.png")));

The glass pane that is created by the previous code is shown in the next screenshot. As expected, we find that only the portion of alphaList directly below the text is obscured, but the rest of the list is clearly visible.

The fact that we have used ImagePainter to render text does not mean that it is mandatory for a glass pane to incorporate an image, as we could also have used a TextPainter object. It is just that writing diagonally positioned text is very easy when an image is used. In general, any valid painting activity can be used for glass panes.

In order to illustrate the ease with which image orientation can be changed, let us write the same string as in the previous screenshot but rotated by 90°. In order to do this, replace the statement within the try block in the code shown earlier for installing the glass pane with the one shown below:

demoForm.setGlassPane(new ImagePainter(Image.createImage(
"/text.png").rotate(90)));

The following screenshot shows the new Glass Pane:

The rotate method used above assumes that the image to be rotated is a square one. A word of caution here, rotating images through angles that are not multiples of 90° is rather inefficient and should be avoided as far as possible. Also, such angles may not be supported on all platforms.

A GlassPane with multiple layers

A glass pane, like a background, can have as many layers as we want. Our next example, DemoLayeredGP, has two layers. The first layer draws a circle at the center of the pane, and the second draws a six pixel wide band right across its middle. Obviously, the glass pane that we want has to be a painter chain, and we create this chain exactly as we had created the chain for background painters.

Painter[] glassPanes = new Painter[2];
glassPanes[0] = new CirclePainter();
glassPanes[1] = new BandPainter();
PainterChain gpChain = new PainterChain(glassPanes);

Then the painter chain is installed using the same approach as the one for a single layer glass pane in the previous example.

//install glass pane
//using either of the following statements

//PainterChain.installGlassPane(demoForm, gpChain);
demoForm.setGlassPane(gpChain);

The glass pane will now look like the following screenshot with the band over the circle. Observe that both these figures remain stationary even if the list beneath is scrolled.

We can reverse the order of the two panes simply by changing the respective indices in the painter array

glassPanes[1] = new CirclePainter();
glassPanes[0] = new BandPainter();


The circle will now be drawn over the band, as shown in the following screenshot:


Summary

Painters are essentially layers on which we can paint. Such a layer can be placed under the visual elements of a component forming its background. It can also be placed above a form as a normally transparent pane through which the form can be seen. Anything that is rendered on such a pane remains unaffected by changes (such as animations) in the form below.

Painters are convenient tools, for example, when we want custom patterns to be used as backgrounds. This is especially true when we need to support different combinations of such patterns in a range of components. Such variability can be easily programmed by arranging the constituents in layer sets that can be formed into PainterChains. A chain can then be selected for use, depending on the required combination.

There are many instances when a message needs to be superimposed on a UI. Consider an email client, which shows a message overlay that first says "Sending mail..." when the Send command is executed and then changes to "Your mail was successfully sent" upon completion of the activity. Glass panes are very useful for implementing such effects. As in the case of background painters, chains of glass panes can be used to form varied combinations of a set of texts, images, or rendered elements.

In this article, we have studied painters and their applications quite extensively. The four examples have demonstrated the use of both background painters and glass panes—single layered as well as chained.



LWUIT 1.1 for Java ME Developers
 
LWUIT 1.1 for Java ME Developers Create great user interfaces for mobile devices
  • Make your applications stand out with dazzling graphics that look and behave the same on different mobile devices
  • Log information on the runtime behavior of your program
  • Write applications with attractive visual effects like transitions and animations
  • Use localization so that your applications can adapt to different languages and locales
 http://www.packtpub.com/lwuit-1-1-for-java-me-developers/book



Other Relevant Articles from this Category:
Java Hello World
What Is CLASSPATH
Java Interface Overview

More Categories:
Java Script  
Download Java  
Java Game  
Java Programming  
Java Developer  
Java Certification  
Java Applet  
Java Sun Certification  
Java Tutorial  
Java Swing  
Java Runtime Environment  
Xml  
Install Java  
Java Network Programming  
Java Training  
J2ee  
Thinking In Java  
Java Application Server  
Java Programmer  
Java Design Pattern  
Tomcat  
Struts  
Jsp