Swings chapter 15

Chapter 15

Swing Basics

There are two technologies you use when developing desktop user-interface: the Abstract Window Toolkit (AWT) and Swing. You may have heard that the AWT is an old technology—having been in existence since Java 1.0—that has been replaced by Swing. It is true, but it's not time yet to toss the AWT.

Swing is preferred because it has a better collection of ready-to-use components. Swing components are also much more powerful than their AWT counterparts. For one, some Swing components can render HTML tags, something AWT developers would not even dare to dream about. Nonetheless, the AWT is still relevant because Swing relies on the AWT event handling mechanism and layout managers as well as its various classes; therefore you still need to know about those classes. Moreover, when developing applets (See Chapter 20, “Applets”), your knowledge of AWT will come handy in too.

Note

Swing is part of the Java Foundation Classes (JFC), a collection of features for building graphical user interfaces (GUIs) and adding interactivity to Java applications. The JFC was launched at the 1997 JavaOne conference and includes the following technologies: the Java 2D API, Drag-and-Drop support, internationalization, pluggable Look-and-Feel support, and the Accessibility API.



There are three things you need to learn to become an effective UI programmers:

images UI components. These include top-level containers (JFrame, JDialog, etc) and components that can be added to a container.

images Layout managers. How to lay out your components in a container.

images Event handling. How to write code that responds to an event, such as a button click, a mouse move, a window resize, etc.



This chapter starts with AWT components, which will be only briefly discussed. Following it are sections on simple Swing components, such as JFrame, JButton, JLabel, JTextArea, JOptionPane, and JDialog. Chapter 16, “Swinging Higher” focuses on layout management and event handling. In addition, there is discussion of thread-related Swing classes in Chapter 23, “Java Threads” and Chapter 24, “The Concurrency Utilities.”

Note

The main difference between AWT and Swing lies in how they draw graphic components. AWT calls the native GUI functions of the operating system to do that. This means, programs that use AWT will look different on Windows and on Unix. The term ‘peer’ is often used when describing this approach. When you invoke an AWT method to draw a button, AWT will in turn delegate the task to a ‘peer’ native function. However, writing high-quality drawing methods that rely on native functions proves to be difficult because the native operating system does not always have a necessary function that can be used to perform certain functionality. As a result, Sun Microsystems invented Swing. Swing draws all its UI components itself, hence eliminating dependence on native peers. With Swing, a GUI program will look the same everywhere, be in on Linux, Mac, or Windows. (In practice, this is not really true.) In older machines, the side-effect of having to draw everything itself is that Swing programs look a little sluggish, because of course it takes more time than if the same graphics were displayed using native functions. However, with today's computers, it is no longer a problem.

AWT Components

AWT components are grouped into the java.awt package. At its core is the Component class, which is a direct subclass of java.lang.Object. This is described in Figure 15.1.

images

Figure 15.1: AWT components

The Component class has subclasses that represent components that you can draw on your UI program:

images  Button. Represents a clickable button.

images  Canvas. Represents a blank screen you can draw custom paintings on.

images  Checkbox. Represents a check box.

images  Choice. Represents a radio button.

images  Container. Represents a component that can contain other components.

images  Label. Represents a non-editable piece of text.

images  List. Represents a list of options.

images  Scrollbar. Represents horizontal and vertical scrollbars.

images  TextComponent. A parent class of two concrete classes: TextArea and TextField. TextField can contain a single line of text and TextArea multiple lines of text.



Of special interest is the Container class. You can add components to a Container using one of its add methods. A concrete implementation of Container is Window, which is the parent of the Frame class. Even though you can instantiate Window, more often you will use a Frame or Dialog to contain other components because Frame and Dialog are easier to use and have more features than Window. Frame and Dialog are similar, except for the fact that Dialog is often used to take user input. Almost all AWT applications will have at least one Frame.

The Frame class offers the following methods:

images  setTitle. Sets the frame's title.

images  add. Adds an AWT component on to the frame.

images  remove. Removes an AWT component from the frame.

images  show. Displays this Frame.



In a typical AWT application, you normally start your program by constructing an instance of Frame and adding components to it. Listing 15.1 features the AWTFrameTest class that adds various AWT components to a Frame.

Listing 15.1: Using AWT components


package app15;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;

public class AWTFrameTest extends Frame {
    public static void main(String[] args) {
        AWTFrameTest frame = new AWTFrameTest();
        frame.setTitle("My AWT Frame");
        frame.setSize(300, 100);
        frame.setLayout(new FlowLayout());
        // add components
        Label label = new Label("Name");
        frame.add(label);
        TextField textField = new TextField();
        frame.add(textField);
        Button button = new Button("Register");
        frame.add(button);
        Checkbox checkbox = new Checkbox();
        frame.add(checkbox);
        frame.setVisible(true);
    }
}

The AWTFrameTest class extends java.awt.Frame. After you create a Frame, you can call its setTitle method and pass a String for its title. You can also invoke the setSize method to set the frame's width and height in pixels.

The line in bold in Listing 15.1 is a call to the setLayout method. You pass a LayoutManager to this method and the object will determine how child components added to a frame are laid out. We will discuss LayoutManager further in Chapter 16, “Swinging Higher.”

You can add components to a frame by using the add method of the Frame class. In Listing 15.1, we added four components, a Label, a TextField, a Checkbox, and a Button. Finally, the setVisible method is invoked to make the frame visible.

If you run the AWTFrameTest class, you will see something like Figure 15.2. Its actual appearance depends on the operating system the program is running on.


Figure 15.2: An AWT Frame and some components

The frame in Figure 15.2 has a size of 300 by 100 pixels. Its title says “My AWT Frame.” There are four components added to it.

Note

The close button (indicated by X) does not close the frame. In fact, making an AWT frame closable by a single click is not straight-forward. This has been remedied in Swing, which is one of the reasons Swing is better and easier to program.



The GUI application in Figure 15.2 looks good enough for introduction, but you can do more with the AWT library. You can add menus and submenus, write code that responds to an event (such as a button click or window resize), use a layout manager to lay out components, and so on. We will not delve into AWT components deeper because we want to focus on Swing.

Useful AWT Classes

In addition to AWT classes that are parents to Swing components, there are other classes that are often used in Swing applications. These classes are discussed in this section.

java.awt.Color

A Color represents a color. Creating a Color object is supereasy because the Color class provides static fields that return a specific Color. The names of these fields are the same as the colors they represent. Here are some of the static final fields in Color: BLACK, BLUE, GREEN, RED, CYAN, ORANGE, YELLOW.

For example, here is how you obtain a green Color:

Color color = Color.GREEN;

You can also create a custom color by passing red-green-blue (RGB) values to the Color class's constructor. For example:

Color myColor = new Color(246, 27, 27);

To change a component's color, call the setForeGround and setBackGround methods of the component.


component.setForeGround(Color.YELLOW) ;
component.setBackGround(Color.RED);

java.awt.Font

A Font represents a font. Here is a constructor of the Font class.

public Font(java.lang.String name, int style, int size)

Here, name is the font name (such as “Verdana”, “Arial”, etc) and size is the point size of the font. The style argument takes an integer bitmask that may be PLAIN or a bitwise union of BOLD and/or ITALIC.

For example, the following code construct a Font object.

int style = Font.BOLD | Font.ITALIC;
Font font = new Font("Garamond", style , 11);

java.awt.Point

A Point represents a point in a coordinate system. It has two int fields, x and y. You can construct a Point object by using one of its constructors.


public Point()

public Point(int x, int y)

public Point(Point anotherPoint)

The Point class's getX and getY methods return the value of the x and y fields in double, respectively.

java.awt.Dimension

A Dimension represents a width and a height in int. It is meant to represent the dimension of an AWT or Swing component. There are two int fields, width and height. The getWidth and getHeight methods return a double, not an int. You can construct an instance of Dimension by using one of its constructors:


public Dimension()

public Dimension(Dimension d)

public Dimension(int width, int height)

The no-arg constructor creates a Dimension with a zero width and height.

java.awt.Rectangle

A Rectange specifies a rectangular area in the coordinate system. Its x and y fields specify the top-left corner coordinate. Its width and height fields specify the width and height of the rectangle, respectively.

Here are some of the constructors of Rectangle.


public Rectangle()

public Rectangle(Dimension d)

public Rectangle(int width, int height)

public Rectangle(int x, int y, int width, int height)

java.awt.Graphics

The Graphics class is an abstract class for rendering AWT and Swing components. You need to work with a Graphics if you want to change the appearance of a component, create a custom component, and so on. To do this, you override the component's paint method:

public void paint(Graphics graphics)

The overridden method takes a Graphics that you can use to paint your component. After you obtain a Graphics, you can call its various methods to draw on it. Here are some of the methods in Graphics: drawArc, drawChars, drawImage, drawLine, drawOval, drawPolygon, drawPolyline, drawRect, drawString, fillArc, fillOval, etc.

java.awt.Toolkit

The Toolkit abstract class has the following methods that make it interesting.

public static Toolkit getDefaultToolkit()

Returns the default implementation of the Toolkit class.

public abstract void beep()

Produces a beep sound.

public abstract Dimension getScreenSize()

Returns a java.awt.Dimension object containing the width and the height of the screen.

Basic Swing Components

Swing is the Java technology for developing desktop applications that need graphical user interface (GUI), replacing AWT but still using the AWT event model. As a technology, Swing is mature and complete, its rich set of classes and interfaces spanning across 17 packages. Swing components are contained in the javax.swing package. Figure 15.3 depicts the class hierarchy of Swing components. To save space, all classes with no package name belong to the javax.swing package.


Comments

Popular posts from this blog

My Response is on my own Website : Best Quality Backlink Strategy

Why is Digital Marketing Important? What are the Advantages of Digital Marketing?

Hottest Snapchat girls usernames online