Showing posts with label java swing. Show all posts
Showing posts with label java swing. Show all posts

Friday, May 27, 2011

Using Colors

Now that we know how to create various 2D shapes, the next step would be to use colors in our UI components. Not everything looks fine in black and white. Colors bring some radiance and class to the look and feel of a UI component. In this chapter, we are going to learn how to do just that.

So, lets get started!!!

Using Colors:

The setPaint method of the Graphics2D class lets you select a color that will be used for all subsequent drawing operations on the graphics context. For example:

g2.setPaint(Color.RED);
g2.drawString("Caution!", 100, 100);

You can fill the interiors of closed shapes (such as rectangles or ellipses) with a color. Simply call fill instead of draw:

Rectangle2D rect = . . .;
g2.setPaint(Color.RED);
g2.fill(rect); // fills the rect object with red color

To draw in multiple colors, you select a color, draw or fill, then select another color, and draw or fill again.

You define colors with the Color class. The java.awt.Color class offers predefined constants for the following 13 standard colors:

BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW

You can specify a custom color by creating a Color object by its red, green, and blue components. Using a scale of 0–255 (that is, one byte) for the redness, blueness, and greenness and then invoke the Color constructor like below:

Color(int redness, int greenness, int blueness)

Example:
g2.setPaint(new Color(0, 128, 128));
g2.drawString("Welcome!", 75, 125);

To set the background color, you use the setBackground method of the Component class, an ancestor of JComponent.

MyComponent p = new MyComponent();
p.setBackground(Color.MAGENTA);

There is also a setForeground method. It specifies the default color that is used for drawing on the component.

Trivia:
The brighter() and darker() methods of the Color class produce, as their names suggest, either brighter or darker versions of the current color. Using the brighter method is also a good way to highlight an item. Actually, brighter() is just a little bit brighter. To make a color really stand out, apply it three times: c.brighter().brighter().brighter().

Java gives you predefined names for many more colors in its SystemColor class. The constants in this class encapsulate the colors used for various elements of the user’s system. For example,
p.setBackground(SystemColor.window)

sets the background color of the component to the default used by all windows on the user’s desktop.

Using the colors in the SystemColor class is particularly useful when you want to draw user interface elements so that the colors match those already found on the user’s desktop.

Let us now take a look at all the possible color options available in the System Color class and their usage.
Name Usage/Purpose
desktop Background color of desktop
activeCaption Background color for captions
activeCaptionText Text color for captions
activeCaptionBorder Border color for caption text
inactiveCaption Background color for inactive captions
inactiveCaptionText Text color for inactive captions
inactiveCaptionBorder Border color for inactive captions
window Background for windows
windowBorder Color of window border frame
windowText Text color inside windows
menu Background for menus
menuText Text color for menus
text Background color for text
textText Text color for text
textInactiveText Text color for inactive controls
textHighlight Background color for highlighted text
textHighlightText Text color for highlighted text
control Background color for controls
controlText Text color for controls
controlLtHighlight Light highlight color for controls
controlHighlight Highlight color for controls
controlShadow Shadow color for controls
controlDkShadow Dark shadow color for controls
scrollbar Background color for scrollbars
info Background color for spot-help text
infoText Text color for spot-help text

Prev: Creating a 2D Shape

Next: Using Special Fonts for Text

Displaying Text in a Component

In the previous chapters, we learnt how to create a frame and then how to size and position it. The next step is to start putting stuff inside a frame. Seeing empty frames is kind of boring, isnt it…

So, lets get started!!!

Displaying Information in a Frame

In this chapter, we are going to learn how to add a component into a Frame. This component is going to be pretty straight forward that writes out some text onto the frame.

As a first step, we need to know how to add a component to the frame. The code to add a component to a frame looks like below:

Container contentPane = frame.getContentPane();
Component c = . . .;
contentPane.add(c);

When you add a component to a frame, you are actually adding the component to the frame’s content pane.

Or, you can use a short cut. As of Java SE 5.0, you can simply use the call

frame.add(c);

This will in-turn call the content pane’s add method.

In our case, we want to add a single component to the frame on which we will write out our message. To draw on a component, you define a class that extends JComponent and override the paintComponent method in that class.

The paintComponent method takes one parameter of type Graphics. A Graphics object remembers a collection of settings for drawing images and text, such as the font you set or the current color. All drawing in Java must go through a Graphics object. It has methods that draw patterns, images, and text.

Here’s how to make a component onto which you can draw/write stuff:

class MyComponent extends JComponent
{
public void paintComponent(Graphics g)
{
//code for drawing
}
}

Each time a window needs to be redrawn, no matter what the reason, the event handler notifies the component. This causes the paintComponent methods of all components to be executed.
Never call the paintComponent method yourself. It is called automatically whenever a part of your application needs to be redrawn, and you should not interfere with this automatic process.

Trivia:
What kind of actions triggers this automatic response? For example, painting occurs because the user increased the size of the window or minimized and then restored the window. If the user popped up another window and it covered an existing window and then made the overlaid window disappear, the application window that was covered is now corrupted and will need to be repainted. (The graphics system does not save the pixels underneath.) And, of course, when the window is displayed for the first time, it needs to process the code that specifies how and where it should draw the initial elements.

As you saw in the code fragment above, the paintComponent method takes a single parameter of type Graphics. Measurement on a Graphics object for screen display is done in pixels. The (0, 0) coordinate denotes the top-left corner of the component on whose surface you are drawing.

Displaying Text in our Component:

Displaying text is considered a special kind of drawing. The Graphics class has a drawString method that has the following syntax:

g.drawString(text, x, y)

In our case, we want to draw the string "Welcome to Java Swings Tutorial!!!" in our original window, roughly one-quarter of the way across and halfway down. Although we don’t yet know how to measure the size of the string, we’ll start the string at coordinates (75, 100). This means the first character in the string will start at a position 75 pixels to the right and 100 pixels down.

Thus, our paintComponent method will look like this:

class TestPaintComponent extends JComponent
{
public void paintComponent(Graphics g)
{
g.drawString("Welcome to Java Swings Tutorial!!!", MESSAGE_X, MESSAGE_Y);
}

public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
}

Let us now take a look at a fully functional class that will write out some text in our frame:


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

/**
* @version 1.0 24-May-2011
* @author Anand Vijayakumar
*/
public class PrintSomethingInFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

/**
* A frame that contains a message panel
*/
class TestFrame extends JFrame
{
public TestFrame()
{
setTitle("Print Something");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add panel to frame

TestPaintComponent comp = new TestPaintComponent();
add(comp);
}

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

/**
* A Component that displays a message.
*/
class TestPaintComponent extends JComponent
{
public void paintComponent(Graphics g)
{
g.drawString("Welcome to Java Swings Tutorial!!!", MESSAGE_X, MESSAGE_Y);
}

public static final int MESSAGE_X = 50;
public static final int MESSAGE_Y = 75;
}


If you run this class you will see something like below:


Prev: Positioning a Frame

Next: Creating 2D Shapes

Tuesday, May 24, 2011

Introduction to Java Swings

Well, finally I have begun writing articles for these topics on Advanced Java Concepts. We begin with the first part, which is UI Programming with Java Swings. This chapter is just an introduction to this great technology.

So, lets get started!!!

Before Java Swings – Abstract Window Toolkit (AWT)

When Java 1.0 was introduced, it contained a class library, which Sun called the Abstract Window Toolkit (AWT), for basic GUI programming. The basic AWT library deals with user interface elements by delegating their creation and behavior to the native GUI toolkit on each target platform (Windows, Solaris, Macintosh, and so on). For example, if you used the original AWT to put a text box on a Java window, an underlying “peer” text box actually handled the text input. The resulting program could then, in theory, run on any of these platforms, with the “look and feel” of the target platform; hence Sun’s trademarked slogan “Write Once, Run Anywhere.”

The peer-based approach worked well for simple applications, but it soon became apparent that it was pretty difficult to write a high-quality portable graphics programs that depended on native user interface elements. User interface elements such as menus, scrollbars, and text fields can have subtle differences in behavior on different platforms. It was hard, therefore, to give users a consistent and most importantly a predictable experience with this approach. Moreover, some graphical environments (such as X11/Motif) do not have as rich a collection of user interface components when compared to Windows or the Mac. This further limits a portable library based on peers to a “lowest common denominator” approach. As a result, GUI applications built with the AWT simply did not look as nice as native Windows or Macintosh applications, nor did they have the kind of functionality that users of those platforms wanted or expected.

The nail on the coffin was the fact that, the code did not just work the same way in different platforms. Unfortunately developers were forced to test out their code in the different platforms before they could release them, effectively killing the motto of Write Once, Run Anywhere.

Birth of Swings from Netscape IFC

In 1996, Netscape created a GUI library they called the IFC (Internet Foundation Classes) that used a totally different approach. User interface elements, such as buttons, menus, and so on, were painted onto blank windows. The only functionality required from the underlying windowing system was a way to put up windows and to paint on the window. Thus, Netscape’s IFC widgets looked and behaved the same no matter which platform the program ran on. Sun worked with Netscape to perfect this approach, creating a user interface library with the code name “Swing.” Swing was available as an extension to Java 1.1 and became a part of the standard library in Java SE 1.2.

Note
Swing is not a complete replacement for the AWT—it is built on top of the AWT architecture. Swing simply gives you more capable user interface components.

Of course, Swing-based user interface elements will be somewhat slower to appear on the user’s screen than the peer-based components used by the AWT. The point here is that, given the processing power of the modern computers, this shouldn't be a problem at all.

Why Java Swings?

Even though AWT is powerful, there are many compelling reasons as to why Swings is a more successful and preferred choice for UI programmers. They are:

1. Swing has a rich and convenient set of user interface elements.
2. Swing has few dependencies on the underlying platform. This means that it is less prone to platform-specific bugs.
3. Swing gives a consistent user experience across platforms.

But, the third advantage is also a potential drawback. If the UI elements look the same on all platforms, then they will look different from the native controls and thus users will be less familiar with them.

Swing solves this problem in a very elegant way. Programmers writing Swing programs can give the program a specific “look and feel.” This way, the users using the system wouldn't be confused by the look and feel of the system.

Next: Creating a Frame
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers