20
GUI development in GUI development in Java Java L. Grewe L. Grewe

GUI development in Java

  • Upload
    tracey

  • View
    53

  • Download
    1

Embed Size (px)

DESCRIPTION

GUI development in Java. L. Grewe. Two methodologies for things to appear on the screen. By painting / drawing e.g. drawing an Image By the creation and addition of GUI elements. e.g. create Button and add it to the GUI. Painting / Drawing to Interface. - PowerPoint PPT Presentation

Citation preview

Page 1: GUI development in Java

GUI development in GUI development in JavaJava

L. GreweL. Grewe

Page 2: GUI development in Java

Two methodologies for things to Two methodologies for things to appear on the screenappear on the screen

1.1. By painting / drawingBy painting / drawing e.g. drawing an Imagee.g. drawing an Image

2.2. By the creation and addition of GUI By the creation and addition of GUI elements.elements.

e.g. create Button and add it to the GUI.e.g. create Button and add it to the GUI.

Page 3: GUI development in Java

Painting / Drawing to InterfacePainting / Drawing to Interface

Have an GUI element you can draw in, e.g. Have an GUI element you can draw in, e.g. Graphics object associated with a GUI Graphics object associated with a GUI component class like a panel.component class like a panel.• Applications will have windows and panels that Applications will have windows and panels that

can grab Graphics object from.can grab Graphics object from.• Applets have method called paint(Graphics g) Applets have method called paint(Graphics g)

that gives you the Graphics object.that gives you the Graphics object.

Graphics class has methods draw*Graphics class has methods draw* Look at current API for complete list of Look at current API for complete list of

methods.methods.

Page 4: GUI development in Java

A Graphics objectA Graphics object

Made up of pixels, Made up of pixels, origin is in upper origin is in upper left hand corner.left hand corner.

Most draw* Most draw* methods based on methods based on pixel coordinates.pixel coordinates.

Page 5: GUI development in Java

Example of simple drawingExample of simple drawing//Purpose: Draws Squares//Purpose: Draws Squares

import java.awt.Graphics; //Graphics Classesimport java.awt.Graphics; //Graphics Classes import java.applet.Applet; //Applet Class import java.applet.Applet; //Applet Class import java.awt.Color; //Color Class import java.awt.Color; //Color Class

public class test5 extends Applet {public class test5 extends Applet { public Color color1, color2, color3, background; public Color color1, color2, color3, background;

public void init() { public void init() { color1 = new Color(255,0,0); color1 = new Color(255,0,0); color2 = new Color(0,255,0);color2 = new Color(0,255,0);color3 = new Color(0,0,255);color3 = new Color(0,0,255);background = new Color(255,255,255); } background = new Color(255,255,255); }

public void paint(Graphics g) { public void paint(Graphics g) { g.setColor( background ); g.setColor( background ); g.fillRect(0,0,100,200); g.fillRect(0,0,100,200); g.setColor( color1 ); g.setColor( color1 ); g.fillRect(0,0,100,100); g.fillRect(0,0,100,100); g.setColor( color2 ); g.setColor( color2 ); g.fillRect(20,20,60,60); g.fillRect(20,20,60,60); g.setColor( color3 ); g.setColor( color3 ); g.fillRect(40,40,20,20); } g.fillRect(40,40,20,20); }

} }

Page 6: GUI development in Java

Drawing an ImageDrawing an Image//Purpose: Open an image from the same directory as the //Purpose: Open an image from the same directory as the

web-page web-page // that includes this applet and display it to the screen.// that includes this applet and display it to the screen. import java.awt.*;import java.awt.*; import java.applet.Applet; import java.applet.Applet;

public class test7 extends Applet { public class test7 extends Applet { Image butch; Image butch;

public void init() { public void init() { butch = getImage(getDocumentBase(), "B.jpg"); } butch = getImage(getDocumentBase(), "B.jpg"); }

//draw as must as you can of the image. //draw as must as you can of the image. // Note that we use the Applet itself (this) as // Note that we use the Applet itself (this) as // an object that implements the ImageObserver interface // an object that implements the ImageObserver interface // the applet inheirits this from is Component superclass. // the applet inheirits this from is Component superclass. // this monitors the loading of the Image. // this monitors the loading of the Image. public void paint(Graphics g) public void paint(Graphics g)

{ g.drawImage(butch, 0, 0, this); } { g.drawImage(butch, 0, 0, this); } } }

Page 7: GUI development in Java

GUI ComponentsGUI Components

The Idea:The Idea:1.1. Setup container’s layout:Setup container’s layout:

• Container is object which will hold the components Container is object which will hold the components you will create. (e.g. Panel/JPanel)you will create. (e.g. Panel/JPanel)

• Layout refers to how you place components in the Layout refers to how you place components in the container.container.

2.2. Create a GUI Component (e.g Button/JButton)Create a GUI Component (e.g Button/JButton)

3.3. Add the component to the container of choiceAdd the component to the container of choice

Page 8: GUI development in Java

Java GUI ClassesJava GUI Classes AWT (Abstract Window Toolkit) (java.awt.*)AWT (Abstract Window Toolkit) (java.awt.*)

• Old GUI framework for Java (Java 1.1)Old GUI framework for Java (Java 1.1)• Some reliance on native code counterpartsSome reliance on native code counterparts• Platform independence problemsPlatform independence problems

Swing (javax.swing.*)Swing (javax.swing.*)• New GUI framework first introduced in Java 1.2New GUI framework first introduced in Java 1.2• Includes AWT features plus many enhancementsIncludes AWT features plus many enhancements• Pure Java components (no reliance on native code)Pure Java components (no reliance on native code)• Pluggable look and feel architecturePluggable look and feel architecture

SWT (Standard Widget Toolkit; from Eclipse) and SWT (Standard Widget Toolkit; from Eclipse) and others???others???

Page 9: GUI development in Java

Lightweight vs. HeavyweightLightweight vs. HeavyweightSwing vs. AWTSwing vs. AWT

A A heavyweightheavyweight component is one that is associated with its own native screen component is one that is associated with its own native screen resource (commonly known as a resource (commonly known as a peerpeer). ).

A A lightweightlightweight component is one that "borrows" the screen resource of an component is one that "borrows" the screen resource of an ancestor (which means it has no native resource of its own -- so it's "lighter"). ancestor (which means it has no native resource of its own -- so it's "lighter").

Lightweight components sit on top of heavyweight components.Lightweight components sit on top of heavyweight components. Always, ALWAYS, use lightweight (Swing or “J”) components when you can.Always, ALWAYS, use lightweight (Swing or “J”) components when you can. All AWT components are heavyweight and all Swing components are All AWT components are heavyweight and all Swing components are

lightweight, except for the top-level ones:lightweight, except for the top-level ones:• JWindowJWindow• JFrameJFrame• JDialogJDialog• JAppletJApplet

The differences boil down to the following: The differences boil down to the following: • A lightweight component can have transparent pixels; a heavyweight is always A lightweight component can have transparent pixels; a heavyweight is always

opaque. opaque. • A lightweight component can appear to be non-rectangular because of its ability to A lightweight component can appear to be non-rectangular because of its ability to

set transparent areas; a heavyweight can only be rectangular. set transparent areas; a heavyweight can only be rectangular. • Mouse events on a lightweight component fall through to its parent; mouse events Mouse events on a lightweight component fall through to its parent; mouse events

on a heavyweight component do not fall through to its parent. on a heavyweight component do not fall through to its parent. • When a lightweight component overlaps a heavyweight component, the When a lightweight component overlaps a heavyweight component, the

heavyweight component is always on top, regardless of the relative z-order  of the heavyweight component is always on top, regardless of the relative z-order  of the two components. two components.

From: From: http://java.sun.com/products/jfc/tsc/articles/mixing/

Page 10: GUI development in Java

GUI ContainersGUI Containers

There are a number of classes that There are a number of classes that are containers. Some Examples:are containers. Some Examples:

Frame/JFrame Frame/JFrame Panel/JPanelPanel/JPanel Applet/JAppletApplet/JApplet

Page 11: GUI development in Java

GUI HierarchyGUI Hierarchy Here is one hierarchy traceHere is one hierarchy trace

• ObjectObject ComponentComponent

• ContainerContainer JContainerJContainer

GUI components inherit from Component.GUI components inherit from Component.

Container is a GUI component that can hold other Container is a GUI component that can hold other components.components.• Notice that Container is a Component so Containers can Notice that Container is a Component so Containers can

be added to other Containers.be added to other Containers.

JContainer is the lightweight version of Container JContainer is the lightweight version of Container and is, therefore, the superclass of all lightweight and is, therefore, the superclass of all lightweight Swing components.Swing components.

Page 12: GUI development in Java

Some Basic Layout ManagersSome Basic Layout Managers FlowLayoutFlowLayout

• Default for some containersDefault for some containers• Adds in order, from upper left to bottom right.Adds in order, from upper left to bottom right.

BorderLayoutBorderLayout• Adds to one of 5 areas of the screen.Adds to one of 5 areas of the screen.• Default for JFrame.Default for JFrame.

GridLayoutGridLayout• Rows and column layout.Rows and column layout.• My favorite – fast and easy.My favorite – fast and easy.

GridBagLayoutGridBagLayout• Like GridLayout, but much more complex.Like GridLayout, but much more complex.• Uses Constraints to position Components.Uses Constraints to position Components.

BoxLayoutBoxLayout• laid out either vertically or horizontally. The components will not wrap laid out either vertically or horizontally. The components will not wrap

so, for example, a vertical arrangement of components will stay so, for example, a vertical arrangement of components will stay vertically arranged when the frame is resized. vertically arranged when the frame is resized.

nullnull• This means NO layout manager, you can use methods on Components This means NO layout manager, you can use methods on Components

to set their location exactly in terms of pixel location in the container.to set their location exactly in terms of pixel location in the container.

Page 13: GUI development in Java

Some Additional Layout Some Additional Layout Managers….here is one from swingManagers….here is one from swing

GroupLayoutGroupLayout• hierarchically groups components in order to position them in a Container. hierarchically groups components in order to position them in a Container.

GroupLayout GroupLayout is intended for use by buildersis intended for use by builders, but may be hand-coded as , but may be hand-coded as wellwell

• Grouping is done by instances of the Grouping is done by instances of the Group class. GroupLayout supports two class. GroupLayout supports two types of groups. A sequential group positions its child elements sequentially, types of groups. A sequential group positions its child elements sequentially, one after another. A parallel group aligns its child elements in one of four one after another. A parallel group aligns its child elements in one of four ways. ways.

• GroupLayout treats each axis independently. That is, there is a group GroupLayout treats each axis independently. That is, there is a group representing the representing the horizontal axishorizontal axis, and a group representing the , and a group representing the vertical axisvertical axis. . The horizontal group is responsible for determining the minimum, preferred The horizontal group is responsible for determining the minimum, preferred and maximum size along the horizontal axis as well as setting the x and width and maximum size along the horizontal axis as well as setting the x and width of the components contained in it. The vertical group is responsible for of the components contained in it. The vertical group is responsible for determining the minimum, preferred and maximum size along the vertical axis determining the minimum, preferred and maximum size along the vertical axis as well as setting the y and height of the components contained in it. as well as setting the y and height of the components contained in it.

• Each Component must exist in both a horizontal and vertical groupEach Component must exist in both a horizontal and vertical group, otherwise , otherwise an IllegalStateException is thrown during layout, or when the minimum, an IllegalStateException is thrown during layout, or when the minimum, preferred or maximum size is requested.preferred or maximum size is requested.

Page 14: GUI development in Java

GroupLayout managerGroupLayout manager• The following diagram shows a sequential group along the horizontal axis. The The following diagram shows a sequential group along the horizontal axis. The

sequential group contains three components. A parallel group was used along sequential group contains three components. A parallel group was used along the vertical axis. the vertical axis.

• The following diagram shows the same three components, but with the parallel The following diagram shows the same three components, but with the parallel group along the horizontal axis and the sequential group along the vertical group along the horizontal axis and the sequential group along the vertical axis. Note C1, the largest element determines the size of the parallel group axis. Note C1, the largest element determines the size of the parallel group along horizontal axis.along horizontal axis.

Page 15: GUI development in Java

GroupLayout managerGroupLayout manager• The following diagram shows a sequential group along both the horizontal and The following diagram shows a sequential group along both the horizontal and

vertical axis. vertical axis.

Page 16: GUI development in Java

Example using GroupLayout from Oracle Java APIExample using GroupLayout from Oracle Java APIThe following builds a panel consisting of two labels in one column, followed by two textfields in the next column: The following builds a panel consisting of two labels in one column, followed by two textfields in the next column:

JComponent panel = ...; JComponent panel = ...;

GroupLayout layout = new GroupLayout(panel); GroupLayout layout = new GroupLayout(panel);

panel.setLayout(layout); // Turn on automatically adding gaps between components panel.setLayout(layout); // Turn on automatically adding gaps between components

layout.setAutoCreateGaps(true); // Turn on automatically creating gaps between components that touch layout.setAutoCreateGaps(true); // Turn on automatically creating gaps between components that touch

// the edge of the container and the container. // the edge of the container and the container.

layout.setAutoCreateContainerGaps(true); // Create a sequential group for the horizontal axis. layout.setAutoCreateContainerGaps(true); // Create a sequential group for the horizontal axis.

GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();

// The sequential group in turn contains two parallel groups. // The sequential group in turn contains two parallel groups.

// One parallel group contains the labels, the other the text fields. // One parallel group contains the labels, the other the text fields.

// Putting the labels in a parallel group along the horizontal axis // Putting the labels in a parallel group along the horizontal axis

// positions them at the same x location. // // positions them at the same x location. //

// Variable indentation is used to reinforce the level of grouping. // Variable indentation is used to reinforce the level of grouping.

hGroup.addGroup(layout.createParallelGroup(). addComponent(label1).addComponent(label2)); hGroup.addGroup(layout.createParallelGroup(). addComponent(label1).addComponent(label2));

hGroup.addGroup(layout.createParallelGroup(). addComponent(tf1).addComponent(tf2)); hGroup.addGroup(layout.createParallelGroup(). addComponent(tf1).addComponent(tf2));

layout.setHorizontalGroup(hGroup); layout.setHorizontalGroup(hGroup);

// Create a sequential group for the vertical axis. G// Create a sequential group for the vertical axis. G

roupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); roupLayout.SequentialGroup vGroup = layout.createSequentialGroup();

// The sequential group contains two parallel groups that align // The sequential group contains two parallel groups that align

// the contents along the baseline. The first parallel group contains // the contents along the baseline. The first parallel group contains

// the first label and text field, and the second parallel group contains // the first label and text field, and the second parallel group contains

// the second label and text field. By using a sequential group // the second label and text field. By using a sequential group

// the labels and text fields are positioned vertically after one another. // the labels and text fields are positioned vertically after one another.

vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(label1).addComponent(tf1)); vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(label1).addComponent(tf1));

vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(label2).addComponent(tf2)); vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(label2).addComponent(tf2));

layout.setVerticalGroup(vGroup); When run the following is produced. layout.setVerticalGroup(vGroup); When run the following is produced.

Page 17: GUI development in Java

GUI ComponentsGUI Components

Buttons Buttons (i.e. Button and JButton)(i.e. Button and JButton)

Menus Menus Check Boxes Check Boxes Text Fields Text Fields Scrolling Lists Scrolling Lists

Page 18: GUI development in Java

Many Helper classesMany Helper classes

• Describe properties of other GUI Describe properties of other GUI Components…some examplesComponents…some examples

ColorColor GraphicsGraphics DimensionDimension OtherOther

Page 19: GUI development in Java

Summary …how to Create a GUISummary …how to Create a GUI Container …..Define for example Frame or Applet to hold the Container …..Define for example Frame or Applet to hold the

components. components.

Setup Layout of containerSetup Layout of container

Add components to the frameAdd components to the frame

Later we will learn about event handling, adding listeners to Later we will learn about event handling, adding listeners to GUI componentsGUI components

Page 20: GUI development in Java

Number of ancestorsNumber of ancestors methods including inherited methods including inherited

ones allow for operations such ones allow for operations such as as • resizing, setting properties, resizing, setting properties,

adding components, etc.adding components, etc.

Object

Component

Container

Window

Frame

JFrame

Lets look at an example container Lets look at an example container class….the JFrameclass….the JFrame