You are on page 1of 9

Chapter 11: Building Graphical User Interfaces (GUI) in Java (3 hrs) Chapter Objective: Describe the Abstract Window

w Toolkit (AWT) package and components Define the terms, components, containers, and layout managers. Use layout managers Use FlowLayout, BorderLayout and GridLayout layout managers to achieve desired GUI layout Add components to a containers Use a Frame and a Panel appropriately. Demonstrate how complex layout manager and nested layout managers works. Introducing AWT then Swing 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 platformhence Suns trademarked slogan Write Once, Run Anywhere. The peer-based approach worked well for simple applications, but it soon became apparent that it was fiendishly difficult to write a high-quality portable graphics library 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 predictable experience with this approach. Moreover, some graphical environments (such as X11/Motif) do not have as rich a collection of user interface components as does Windows or the Macintosh. This in turn 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 had come to expect. More depressingly, there were different bugs in the AWT user interface library on the different platforms. Developers complained that they needed to test their applications on each platform, a practice derisively called write once, debug everywhere. In 1996, Netscape created a GUI library they called the IFC (Internet Foundation Classes) that used an entirely 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, Netscapes 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. Since, as Duke Ellington said, It Dont Mean a Thing If It Aint Got That Swing, Swing is now the official name for the non-peer-based GUI toolkit. Swing is part of the Java Foundation Classes (JFC). The full JFC is vast and contains far more than the Swing GUI toolkit. JFC features not only include the Swing components but also an accessibility API, a 2D API, and a drag-and-drop API. Of course, Swing-based user interface elements will be somewhat slower to appear on the users screen than the peer-based components used by the AWT. Our experience is that on any reasonably modern machine, the speed difference shouldnt be a problem. On the other hand, the reasons to choose Swing are overwhelming: Swing has a rich and convenient set of user interface elements. Swing has few dependencies on the underlying platform; it is therefore less prone to platformspecific bugs. Swing gives a consistent user experience across platforms.

Page 1 of 9

Prepared by: Lawrence G. Decamora III, scjp

Still, the third plus is also a potential drawback: If the user interface 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. Three (3) things that you need to know in developing a GUI Application. 1. Components any visual GUI part of your application. Labels TextFields TextArea Checkboxes 1. Containers Special components in which you can put components within. Frames Panels Dialog 3. Layout Managers FlowLayout BorderLayout GridLayout CardLayout GridBagLayout

AWT stands for Abstract Window Toolkit. It is a Java package that contains classes for visual components. In creating a GUI application, you need to import java.awt.* package. Creating a Frame A top-level window (that is, a window that is not contained inside another window) is called a Frame in Java. The AWT library has a class, called Frame, for this top level. The Swing version of this class is called JFrame and extends the Frame class. The JFrame is one of the few Swing components that is not painted on a canvas. Thus, the decorations (buttons, title bar, icons, and so on) are drawn by the users windowing system, not by Swing. Here's a sample GUI application that uses Frames. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import java.awt.*; public class FrameExample { private Frame f; public FrameExample() { f = new Frame("Hello Out There!"); } public void launchFrame() { f.setSize(170,170); f.setBackground(Color.blue); f.setVisible(true); } public static void main(String args[]) { FrameExample guiWindow = new FrameExample(); guiWindow.launchFrame(); }

Page 2 of 9

Prepared by: Lawrence G. Decamora III, scjp

Output: Let's explain each line. Line 1 allows you to import the java.awt.* package. Line 4 allows you to declare a Frame object. Line 7 allows you to create the Frame object with a named title bar. Line 11, allows you to set the size of the Frame, 170, 170 means its 170 pixels horizontal, and 170 pixels vertical. Frames by default are invisible thus you need to set the visibility to true for it to appear when you run it. How about a JFrame? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import java.awt.*; import javax.swing.*; public class FrameExample { private JFrame f; public FrameExample() { f = new JFrame("Hello Out There!"); } public void launchFrame() { f.setSize(170,170); f.setBackground(Color.blue); f.setVisible(true); } public static void main(String args[]) { FrameExample guiWindow = new FrameExample(); guiWindow.launchFrame(); } }

A JFrame is a swing version of an AWT Frame. The only code difference is you need to import javax.swing.* package in line 2 and add 'J' infront of all Frame declarations. Try to compile and run and see the difference. To close or to terminate the application, go to the command prompt terminal and press Ctrl + C. This will be the way to terminate the application for now. Now, let's try to put something inside the Frame, say a Panel. Frames and Panels are both containers. In the next example, you will see that we can nest containers. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import java.awt.*; public class FrameWithPanel { private Frame f; public FrameWithPanel(String title) { f = new Frame(title); } public void launchFrame() { f.setSize(200,200); f.setBackground(Color.blue); f.setLayout(null); // Override default layout manager Panel pan = new Panel();
Prepared by: Lawrence G. Decamora III, scjp

Page 3 of 9

16 17 18 19 20 21 22 23 24 25 26 27 28

pan.setSize(100,100); pan.setBackground(Color.yellow); f.add(pan); f.setVisible(true);

public static void main(String args[]) { FrameWithPanel guiWindow = new FrameWithPanel("Frame with Panel"); guiWindow.launchFrame(); } } This is what the output looks like:

You noticed that containers can be nested, in this example its the Frame and Panel. We normally put a Panel inside a frame for customization purposes. If you want to create your own LayoutManager, then nesting Panels is one way to do it. Common types of Layout Managers: 1. FlowLayout it is the default layout manager of Panels and Applets; it add components from left to right; Alignment is center; You can use its constructor to tune its behavior. import java.awt.*; public class FlowExample { private Frame f; private Button button1; private Button button2; private Button button3; public FlowExample() { f = new Frame("Flow Layout"); button1 = new Button("Ok"); button2 = new Button("Open"); button3 = new Button("Close"); } public void launchFrame() { f.setLayout(new FlowLayout()); f.add(button1); f.add(button2); f.add(button3); f.setSize(100,100); f.setVisible(true); } public static void main(String args[]) { FlowExample guiWindow = new FlowExample(); guiWindow.launchFrame(); }

}
Page 4 of 9

Prepared by: Lawrence G. Decamora III, scjp

2. BorderLayout The BorderLayout is the default layout manager of the Frame class; Components are added at a specified region; the resizing of of the container will also invoke the following adjustment of components: North, South, and Center will adjust horizontally; East, West and Center will adjust vertically.

import java.awt.*; public class BorderExample { private Frame f; private Button bn, bs, bw, be, bc; public BorderExample() { f = new Frame("Border Layout"); bn = new Button("B1"); bs = new Button("B2"); bw = new Button("B3"); be = new Button("B4"); bc = new Button("B5"); } public void launchFrame() { f.add(bn, BorderLayout.NORTH); f.add(bs, BorderLayout.SOUTH); f.add(bw, BorderLayout.WEST); f.add(be, BorderLayout.EAST); f.add(bc, BorderLayout.CENTER); f.setSize(200,200); f.setVisible(true); } public static void main(String args[]) { BorderExample guiWindow2 = new BorderExample(); guiWindow2.launchFrame(); }

Page 5 of 9

Prepared by: Lawrence G. Decamora III, scjp

3. GridLayout The components are added from left to right and from top to bottom; All components are equally sized; The constructor can be used to specify the number of columns and rows.

Complex GUI Application: Simple Calculator: Try to code the next set of Java Applications, and see the output. Try to compare the differences between AWT and Swing Apps. Here's the AWT version: // SimpleCalculator.java import java.awt.*; public class SimpleCalculator { // containers private Frame f; private Panel p1, p2, p3, p4; // components private Label l1, l2, l3; private TextField tf1, tf2, tf3; private Button bAdd, bSub, bMul, bDiv, bQuit; public SimpleCalculator() { f = new Frame("My First GUI App"); p1 p2 p3 p4 = = = = new new new new Panel(); Panel(); Panel(); Panel();

l1 = new Label("First: "); l2 = new Label("Second: "); l3 = new Label("Result: "); tf1 = new TextField(15); tf2 = new TextField(15); tf3 = new TextField(15); bAdd = new Button("+");
Page 6 of 9 Prepared by: Lawrence G. Decamora III, scjp

bSub = new Button("-"); bMul = new Button("*"); bDiv = new Button("/"); bQuit = new Button("Q"); } public void launchFrame() { // no need for us to change the layout manager of the Panels, // use the default. p1.add(l1); p1.add(tf1); p2.add(l2); p2.add(tf2); p3.add(l3); p3.add(tf3); p4.add(bAdd); p4.add(bSub); p4.add(bMul); p4.add(bDiv); p4.add(bQuit); // use GridLayout(4,1) for frame f.setLayout(new GridLayout(4,1)); f.add(p1); f.add(p2); f.add(p3); f.add(p4); f.pack(); f.setVisible(true); } public static void main(String args[]) { SimpleCalculator sc = new SimpleCalculator(); sc.launchFrame(); } } Here's the Swing version: // SimpleCalculatorSwing.java import java.awt.*; import javax.swing.*; public class SimpleCalculatorSwing { // containers private JFrame f; private JPanel p1, p2, p3, p4; // components private JLabel l1, l2, l3;
Page 7 of 9 Prepared by: Lawrence G. Decamora III, scjp

private JTextField tf1, tf2, tf3; private JButton bAdd, bSub, bMul, bDiv, bQuit; public SimpleCalculatorSwing() { f = new JFrame("My First GUI App"); p1 p2 p3 p4 = = = = new new new new JPanel(); JPanel(); JPanel(); JPanel();

l1 = new JLabel("First: "); l2 = new JLabel("Second: "); l3 = new JLabel("Result: "); tf1 = new JTextField(15); tf2 = new JTextField(15); tf3 = new JTextField(15); bAdd = new JButton("+"); bSub = new JButton("-"); bMul = new JButton("*"); bDiv = new JButton("/"); bQuit = new JButton("Q");

public void launchFrame() { // no need to change the layout manager of the Panel objs, // use the default // layout manager, use FlowLayout p1.add(l1); p1.add(tf1); p2.add(l2); p2.add(tf2); p3.add(l3); p3.add(tf3); p4.add(bAdd); p4.add(bSub); p4.add(bMul); p4.add(bDiv); p4.add(bQuit); f.setLayout(new GridLayout(4,1)); f.add(p1); f.add(p2); f.add(p3); f.add(p4); f.pack(); f.setVisible(true);
Page 8 of 9 Prepared by: Lawrence G. Decamora III, scjp

} public static void main(String args[]) { SimpleCalculatorSwing sc = new SimpleCalculatorSwing(); sc.launchFrame(); }

Page 9 of 9

Prepared by: Lawrence G. Decamora III, scjp

You might also like