55
GUI Components – Part 2 Chapter 1

Chapter 1 Intro to GUI - Part 2.pptx

Embed Size (px)

Citation preview

Page 1: Chapter 1 Intro to GUI - Part 2.pptx

GUI Components – Part 2

Chapter 1

Page 2: Chapter 1 Intro to GUI - Part 2.pptx

How to you lay out GUI components in a container?

2

Use a layout manag

er

Page 3: Chapter 1 Intro to GUI - Part 2.pptx

Lesson ObjectivesAt the end of this lesson, you should be able to• Describe the Java GUI API hierarchy• Create user interfaces using frames, panels, and simple GUI

components • Describe the role of layout managers• Use the FlowLayout, GridLayout, and BorderLayout

managers to layout components in a container• Use JPanel as subcontainers• Specify colors and fonts using the Color and Font classes• Apply common features such as borders, tool tips, fonts, and colors

on Swing components• Use borders to visually group user-interface components• Create image icons using the ImageIcon class

3

Page 4: Chapter 1 Intro to GUI - Part 2.pptx

• 4

Introduction to Layout Managers

• Each container has a layout manager to arrange the UI components within the container.– Components are placed in the frame by the

container’s layout manager.

• There are several different layout managers that you can choose from to place components in the desired locations.

4

Page 5: Chapter 1 Intro to GUI - Part 2.pptx

• 5

Creating and Setting Layout Managers

• A layout manager is created using a layout manager class.

• Every layout manager class implements the LayoutManager interface.

• You can set the layout manager for a container using the setLayout(LayoutManager) method.

5

Page 6: Chapter 1 Intro to GUI - Part 2.pptx

• 6

3 Basic Layout Managers

• FlowLayout

• GridLayout

• BorderLayoutNote: By default, the frame’s layout is BorderLayout.

6

Page 7: Chapter 1 Intro to GUI - Part 2.pptx

• 7

Introduction to FlowLayout

• The simplest layout manager.

• The components are arranged in the container from left to right in the order in which they are added. When one row is filled, a new row is started.

• We can specify the way components are aligned by using one of the 3 constants: FlowLayout.RIGHT, FlowLayout.CENTER or FlowLayout.LEFTo If you do not specify the alignment, center alignment is used.

• If you resized the frame, the components are automatically rearranged to fit in it.

7

Page 8: Chapter 1 Intro to GUI - Part 2.pptx

8

A. Open your Chapter1 NetBeans project

B. Create a new Java Main Class named ShowFlowLayout to create the following GUI:

Page 9: Chapter 1 Intro to GUI - Part 2.pptx

import javax.swing.JLabel;import javax.swing.JTextField;import javax.swing.JFrame;import java.awt.FlowLayout;

public class ShowFlowLayout extends JFrame {

public ShowFlowLayout() {

setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20)); add(new JLabel("First Name")); add(new JTextField(8)); add(new JLabel("MI")); add(new JTextField(1)); add(new JLabel("Last Name")); add(new JTextField(8));

9

Page 10: Chapter 1 Intro to GUI - Part 2.pptx

setTitle("ShowFlowLayout");

setSize(200, 200);

setLocationRelativeTo(null);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

}

public static void main(String[] args) {

ShowFlowLayout frame = new ShowFlowLayout();

}

}

10

Page 11: Chapter 1 Intro to GUI - Part 2.pptx

• 11

The FlowLayout Class

java.awt.FlowLayout

-alignment: int

-hgap: int

-vgap: int

+FlowLayout()

+FlowLayout(alignment: int)

+FlowLayout(alignment: int, hgap: int, vgap: int)

The alignment of this layout manager (default: CENTER).

The horizontal gap of this layout manager (default: 5 pixels).

The vertical gap of this layout manager (default: 5 pixels).

Creates a default FlowLayout manager.

Creates a FlowLayout manager with a specified alignment.

Creates a FlowLayout manager with a specified alignment, horizontal gap, and vertical gap.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

11

Page 12: Chapter 1 Intro to GUI - Part 2.pptx

P1 Q3

12

Page 13: Chapter 1 Intro to GUI - Part 2.pptx

• 13

Introduction to GridLayout

• Arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor.

• The components are placed in the grid from left to right, starting with the first row, then the second and so on, in the order in which they are added.

13

Page 14: Chapter 1 Intro to GUI - Part 2.pptx

• 14

GridLayout Constructor

• The constructor of the GridLayout manager is as follows:public GridLayout(int rows, int columns,

int hGap, int vGap)

• Constructs a new GridLayout with the specified number of rows and columns, along with the specified horizontal and vertical gaps between components in the container.

14

Page 15: Chapter 1 Intro to GUI - Part 2.pptx

15

In your Chapter1 NetBeans project, create a new Java Main Class named ShowGridLayout to create the following GUI:

Note• If you resize the frame, the layout of the components remains

unchanged.• All components are given equal size in the container of GridLayout.

Page 16: Chapter 1 Intro to GUI - Part 2.pptx

import javax.swing.JLabel;import javax.swing.JTextField;import javax.swing.JFrame;import java.awt.GridLayout;

public class ShowGridLayout extends JFrame {

public ShowGridLayout() { setLayout(new GridLayout(3, 2)); add(new JLabel("First Name")); add(new JTextField(8)); add(new JLabel("MI")); add(new JTextField(1)); add(new JLabel("Last Name")); add(new JTextField(8));

16

Page 17: Chapter 1 Intro to GUI - Part 2.pptx

setTitle("ShowGridLayout"); setSize(250, 150); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { ShowGridLayout frame = new ShowGridLayout(); }}

17

Page 18: Chapter 1 Intro to GUI - Part 2.pptx

• 18

The GridLayout Class

Note• In FlowLayout and GridLayout, the order in which the

components are added to the container is important.• It determines the location of the components in the container.

java.awt.GridLayout

-rows: int

-columns: int

-hgap: int

-vgap: int

+GridLayout()

+GridLayout(rows: int, columns: int)

+GridLayout(rows: int, columns: int, hgap: int, vgap: int)

The number of rows in this layout manager (default: 1).

The number of columns in this layout manager (default: 1).

The horizontal gap of this layout manager (default: 0).

The vertical gap of this layout manager (default: 0).

Creates a default GridLayout manager.

Creates a GridLayout with a specified number of rows and columns.

Creates a GridLayout manager with a specified number of rows and columns, horizontal gap, and vertical gap.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

18

Page 19: Chapter 1 Intro to GUI - Part 2.pptx

P1 Q4

19

Page 20: Chapter 1 Intro to GUI - Part 2.pptx

• 20

Introduction to BorderLayout

• Divides the container into five areas: East, South, West, North, and Center.

• Components are added to a BorderLayout by using the add(Component, index) method where index is one of the following constants: BorderLayout.EAST BorderLayout.SOUTH BorderLayout.WEST BorderLayout.NORTH or BorderLayout.CENTER

• The components are laid out according to their preferred sizes and where they are placed in the container.

20

Page 21: Chapter 1 Intro to GUI - Part 2.pptx

21

In your Chapter1 NetBeans project, create a new Java Main Class named ShowBorderLayout to create the following GUI:

Note: It is unnecessary to place components to occupy all the areas - the components in each area can stretch to fill any empty space.

Page 22: Chapter 1 Intro to GUI - Part 2.pptx

• 22

The BorderLayout Class

Note:– The North and South components can stretch horizontally,– The East and West components can stretch vertically, – The Centre component can stretch both horizontally and vertically to

fill any empty space.

22

java.awt.BorderLayout

-hgap: int

-vgap: int

+BorderLayout()

+BorderLayout(hgap: int, vgap: int)

The horizontal gap of this layout manager (default: 0).

The vertical gap of this layout manager (default: 0).

Creates a default BorderLayout manager.

Creates a BorderLayout manager with a specified number of horizontal gap, and vertical gap.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

Page 23: Chapter 1 Intro to GUI - Part 2.pptx

• 23

Additional Methods for Layout Managers

E.g:

FlowLayout flowlayout = new FlowLayout();

flowlayout.setAlignment(FlowLayout.RIGHT);

flowlayout.setHgap(10);

flowlayout.setVgap(20);

FlowLayout GridLayout BorderLayout

setAlignment(value);

setHgap(value);

setVgap(value);

setRows(value);setColumns(value);setHgap(value);setVgap(value);

setHgap(value);setVgap(value);

23

Page 24: Chapter 1 Intro to GUI - Part 2.pptx

• 24

Suppose you want to design an interface as follows:

24

• It is difficult to achieve the desired look by placing all the components in a single container.

Page 25: Chapter 1 Intro to GUI - Part 2.pptx

• 25

Use Panels as Subcontainers

• Divide the frame into panels. Panels act as smaller containers to group UI

components.

You can add buttons to one panel, and then add the panel to the frame.

25

Page 26: Chapter 1 Intro to GUI - Part 2.pptx

• 26

Using Panels as Subcontainers• A frame can contain panels and UI components. Panels

are used to group user-interface components.

• Panels can contain other panels.

E.g. FramePanel

User interfacecomponents (UI)

Panel

UI

Panel

UI

Panel

UI

26

Page 27: Chapter 1 Intro to GUI - Part 2.pptx

• 27

Steps for Using Panels1. Create a panel object p1 :

JPanel p1 = new JPanel();

2. Add a GUI component to the panel p1:  p1.add(new JButton(“ButtonName”));

3. Place the panel into the container as follows:add(p1);

or, place the panel into another panel:JPanel p2 = new JPanel();p2.add(p1);

27

Page 28: Chapter 1 Intro to GUI - Part 2.pptx

28

In your Chapter1 NetBeans project, create a new Java Main Class named TestPanels to create the following GUI:

Note: We can also set the layout manager for a panel.• By default, JPanel uses FlowLayout.

Page 29: Chapter 1 Intro to GUI - Part 2.pptx

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

public class TestPanels extends JFrame {

public TestPanels() { JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3));

for (int i = 1; i <= 9; i++) { buttonPanel.add(new JButton("" + i)); }

buttonPanel.add(new JButton("0")); buttonPanel.add(new JButton("Start")); buttonPanel.add(new JButton("Stop"));

29

Page 30: Chapter 1 Intro to GUI - Part 2.pptx

JPanel controlPanel = new JPanel(new BorderLayout()); controlPanel.add(new JTextField("Time to be displayed here"),

BorderLayout.NORTH); controlPanel.add(buttonPanel, BorderLayout.CENTER); add(controlPanel, BorderLayout.EAST); add(new JButton("Food to be placed here"),

BorderLayout.CENTER); setTitle("The Front View of a Microwave Oven"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 250); setVisible(true); }

public static void main(String[] args) { TestPanels frame = new TestPanels(); }} 30

Page 31: Chapter 1 Intro to GUI - Part 2.pptx

P1 - Q5- Q6- Q7- Q8

31

Page 32: Chapter 1 Intro to GUI - Part 2.pptx

The Color ClassYou can set colors for GUI components by using the java.awt.Color class. Colors are made of red, green, and blue components, each of which is represented by a byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model.

Color c = new Color(r, g, b);r, g, and b specify a color by its red, green, and blue components.

Example:Color c = new Color(228, 100, 255);

32

Page 33: Chapter 1 Intro to GUI - Part 2.pptx

Standard Colors13 standard colors (black, blue, cyan, dark gray, gray, green, light gray, magenta, orange, pink, red, white, yellow) are defined as constants in java.awt.Color:BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, and YELLOW.

33

Page 34: Chapter 1 Intro to GUI - Part 2.pptx

Setting Colors

• You can use the following methods to set the component’s background and foreground colors: setBackground(Color c) setForeground(Color c)

• Example:jbt.setBackground(Color.yellow);jbt.setForeground(Color.red);

34

Page 35: Chapter 1 Intro to GUI - Part 2.pptx

35

In your Chapter1 NetBeans project, create a new Java Main Class named TestColor.

Page 36: Chapter 1 Intro to GUI - Part 2.pptx

import javax.swing.*;Import java.awt.BorderLayout;import java.awt.Color;

public class TestColor extends JFrame {

private JButton jbtEast = new JButton("East"); private JButton jbtWest = new JButton("West"); private JButton jbtNorth = new JButton("North"); private JButton jbtSouth = new JButton("South"); private JButton jbtCenter = new JButton("Center");

public TestColor() { jbtEast.setBackground(Color.MAGENTA); jbtEast.setForeground(Color.WHITE);

jbtWest.setBackground(new Color(255, 255, 255)); jbtWest.setForeground(new Color(0, 0, 0));

jbtCenter.setBackground(Color.YELLOW); jbtCenter.setForeground(new Color(100, 50, 200));

36

Page 37: Chapter 1 Intro to GUI - Part 2.pptx

add(jbtEast, BorderLayout.EAST); add(jbtWest, BorderLayout.WEST); add(jbtNorth, BorderLayout.NORTH); add(jbtSouth, BorderLayout.SOUTH); add(jbtCenter, BorderLayout.CENTER); setTitle("TestColor"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 200); setVisible(true); } public static void main(String[] args) { new TestColor(); }}

37

Page 38: Chapter 1 Intro to GUI - Part 2.pptx

The Font Class

Font myFont = new Font(name, style, size);Example:Font myFont = new Font("SansSerif ", Font.BOLD, 16);Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

JButton jbtOK = new JButton("OK“);jbtOK.setFont(myFont);

Font Names• Standard font names that

are supported in all platforms are: SansSerif, Serif, Monospaced, Dialog, or DialogInput.

Font Style• Font.PLAIN (0), Font.BOLD (1), Font.ITALIC (2), and Font.BOLD + Font.ITALIC (3)

38

Page 39: Chapter 1 Intro to GUI - Part 2.pptx

Finding All Available Font Names

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();String[] fontnames =

e.getAvailableFontFamilyNames();for (int i = 0; i < fontnames.length; i++) System.out.println(fontnames[i]);

39

Page 40: Chapter 1 Intro to GUI - Part 2.pptx

40

In your Chapter1 NetBeans project, create a new Java Main Class named TestFont.

Page 41: Chapter 1 Intro to GUI - Part 2.pptx

import java.awt.FlowLayout;import java.awt.Font;import java.awt.GraphicsEnvironment;import javax.swing.*;

public class TestFont extends JFrame {

public TestFont() { GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();

String[] fontNames = e.getAvailableFontFamilyNames(); setLayout(new FlowLayout());

JButton[] buttonArray = new JButton[fontNames.length]; add(new JLabel("Total fonts: " + fontNames.length));

41

Page 42: Chapter 1 Intro to GUI - Part 2.pptx

for (int i = 0; i < fontNames.length; ++i) { buttonArray[i] = new JButton((i+1) + ". " + fontNames[i]);

if (i % 2 == 0) buttonArray[i].setFont(new Font(fontNames[i], Font.BOLD, 16)); else buttonArray[i].setFont(new Font(fontNames[i], Font.BOLD +

Font.ITALIC, 12)); add(buttonArray[i]); } setTitle("TestFont"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(1500, 800); setVisible(true); }}

42

Page 43: Chapter 1 Intro to GUI - Part 2.pptx

BordersYou can set a border on any object of the JComponent class. Swing has several types of borders. To create a titled border, use

new TitledBorder(String title)

To create a line border, use new LineBorder(Color color, int width),

where width specifies the thickness of the line. For example, the following code displays a titled border on a panel:

JPanel panel = new JPanel();panel.setBorder(new TitleBorder(“My Panel”));

43

Page 44: Chapter 1 Intro to GUI - Part 2.pptx

Test Swing Common Features

Component Properties• font • background• foreground• preferredSize• minimumSize• maximumSize

JComponent Properties• toolTipText• border

44

Page 45: Chapter 1 Intro to GUI - Part 2.pptx

45

In your Chapter1 NetBeans project, create a new Java Main Class named TestSwingCommonFeatures.

Page 46: Chapter 1 Intro to GUI - Part 2.pptx

import java.awt.Color;import java.awt.Font;import java.awt.GridLayout;import javax.swing.*;import javax.swing.border.Border;import javax.swing.border.LineBorder;import javax.swing.border.TitledBorder;

public class TestSwingCommonFeatures extends JFrame { private JPanel p1 = new JPanel(); private JButton jbtLeft = new JButton("Left"); private JButton jbtCenter = new JButton("Center"); private JButton jbtRight = new JButton("Right"); public TestSwingCommonFeatures() {

jbtLeft.setBackground(Color.WHITE); jbtCenter.setForeground(Color.GREEN); jbtRight.setToolTipText("This is the Right button");

46

Page 47: Chapter 1 Intro to GUI - Part 2.pptx

p1.add(jbtLeft); p1.add(jbtCenter); p1.add(jbtRight); p1.setBorder(new TitledBorder("Three Buttons"));

Font largeFont = new Font("TimesRoman", Font.BOLD, 20); Border lineBorder = new LineBorder(Color.BLACK, 2); JPanel p2 = new JPanel(new GridLayout(1, 2)); JLabel jlblRed = new JLabel("Red"); JLabel jlblOrange = new JLabel("Orange"); jlblRed.setForeground(Color.RED); jlblOrange.setForeground(Color.ORANGE);

47

Page 48: Chapter 1 Intro to GUI - Part 2.pptx

jlblRed.setFont(largeFont); jlblOrange.setFont(largeFont); jlblRed.setBorder(lineBorder); jlblOrange.setBorder(lineBorder); p2.add(jlblRed); p2.add(jlblOrange); p2.setBorder(new TitledBorder("Two Labels")); setLayout(new GridLayout(2, 1)); add(p1); add(p2); setTitle("TestSwingCommonFeatures"); setSize(300, 150); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }

48

Page 49: Chapter 1 Intro to GUI - Part 2.pptx

P1 Q9

49

Page 50: Chapter 1 Intro to GUI - Part 2.pptx

Image IconsJava uses the javax.swing.ImageIcon class to represent an icon. An icon is a fixed-size picture; typically it is small and used to decorate components. Images are normally stored in image files. You can use new ImageIcon(filename) to construct an image icon. For example, the following statement creates an icon from an image file us.gif in the image directory under the current class path:   ImageIcon icon = new ImageIcon(

getClass().getResource("images/us.gif"));

50

Page 51: Chapter 1 Intro to GUI - Part 2.pptx

51

In your Chapter1 NetBeans project window, 1. Right-click the Source Packages node and choose New >

Java Package2. In the Package Name text field, replace newpackage

with images.3. Click Finish.4. Copy all the image files provided for you in the image

files folder and paste them into the new package images that you have just created.

5. Create a new Java Main Class named TestImageIcon.

Page 52: Chapter 1 Intro to GUI - Part 2.pptx

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

public class TestImageIcon extends JFrame {

private ImageIcon usIcon = new ImageIcon(getClass().getResource("images/us.gif"));

private ImageIcon myIcon = new ImageIcon(getClass().getResource("images/my.jpg"));

private ImageIcon frIcon = new ImageIcon(getClass().getResource("images/fr.gif"));

private ImageIcon ukIcon = new ImageIcon(getClass().getResource("images/uk.gif"));

public TestImageIcon() { setLayout(new GridLayout(1, 4, 5, 5)); add(new JLabel(usIcon)); add(new JLabel(myIcon)); add(new JButton(frIcon)); add(new JButton(ukIcon));

52

Page 53: Chapter 1 Intro to GUI - Part 2.pptx

setTitle("TestImageIcon"); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 100); setVisible(true); } public static void main(String[] args) { new TestImageIcon(); }}

53

Page 54: Chapter 1 Intro to GUI - Part 2.pptx

Swing vs. AWTSo why do the GUI component classes have a prefix J? Instead of JButton, why not name it simply Button? In fact, there is a class already named Button in the java.awt package.

When Java was introduced, the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). For every platform on which Java runs, the AWT components are automatically mapped to the platform-specific components through their respective agents, known as peers. AWT is fine for developing simple graphical user interfaces, but not for developing comprehensive GUI projects. Besides, AWT is prone to platform-specific bugs because its peer-based approach relies heavily on the underlying platform. With the release of Java 2, the AWT user-interface components were replaced by a more robust, versatile, and flexible library known as Swing components. Swing components are painted directly on canvases using Java code, except for components that are subclasses of java.awt.Window or java.awt.Panel, which must be drawn using native GUI on a specific platform. Swing components are less dependent on the target platform and use less of the native GUI resource. For this reason, Swing components that don’t rely on native GUI are referred to as lightweight components, and AWT components are referred to as heavyweight components.

54

Page 55: Chapter 1 Intro to GUI - Part 2.pptx

Review of Lesson ObjectivesYou should now be able to:• Describe the Java GUI API hierarchy• Create user interfaces using frames, panels, and simple GUI

components • Describe the role of layout managers• Use the FlowLayout, GridLayout, and BorderLayout

managers to layout components in a container• Use JPanel as subcontainers• Specify colors and fonts using the Color and Font classes• Apply common features such as borders, tool tips, fonts, and colors

on Swing components• Use borders to visually group user-interface components• Create image icons using the ImageIcon class