Chapter 10 Getting Started with GUI Programming F GUI Class Hierarchy F Frames –Creating frames, centering frames, adding components to frames F Layout.

Slides:



Advertisements
Similar presentations
Chapter 13 Graphics.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 12 Event-Driven Programming 找出画中真谛 — 保罗. 塞尚.
Corresponds with Chapter 12
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 13 GUI Basics.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 14 Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Graphics.
GUI programming AWT(Abstract Windows Toolkit)-GUI components library when Java was introduced AWT was replaced by Swing components import javax.swing.*;
1 GUI Basics First three slides are repeated from previous lecture notes! You will probably (in fact should) never write Java codes like the program examples.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 15 Event-Driven Programming.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
Event-Driven Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L01 (Chapter 13) Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 GUI Basics.
1 Review of applets & Computer Graphis GUILecture 6 Review of Applets & Compute Graphics GUI Overview  Introduction to Graphics. Applets: a quick review.
1 UFCE3T-15-M Object- oriented Design and Programming Block 3 GUI Programming Jin Sa.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L02 (Chapter 13) Graphics.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
GUI Basics: Introduction. Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Steven Holzner, IBM Corp Advanced Java Programming CSE 7345/5345/ NTU 531 Session 7 Welcome Back!!!
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 11 Getting Started.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 12 GUI Basics.
Chapter 10 Getting Started with GUI Programming F GUI Class Hierarchy F Frames –Creating frames, centering frames, adding components to frames F Layout.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 11 Getting Started with GUI Programming 百闻不如一见.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Standard Graphics in Java.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Chapter 8: Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames The relationship between frame and.
1 Chapter 10 Getting Started with Graphics Programming F Graphics Class Hierarchy F Frames –Creating frames, centering frames, adding components to frames.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 Object-Oriented Languages.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
GUI Basics.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 12 GUI Basics.
10/24/20151 Java GUI Programming. 10/24/20152 What is a GUI? Java has standard packages for creating custom Graphical User Interfaces Some of the fundamental.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 Event-Driven Programming.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Agenda Java Coordinate Systems. Graphics Class. Drawing on Panels. Drawing Shapes.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Graphics basic 1. 2 Objectives Understand Java coordinate systems. Draw things using the methods in the Graphics class. Override the paintComponent method.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Basics of GUI Programming Chapter 11 and Chapter 22.
1 Chapter 2 Getting Started with GUI Programming.
Programming 2 LAB TA: Nouf Al-Harbi NoufNaief.net :::
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
1 Chapter 3 Event-Driven Programming. 2 Objectives F To explain the concept of event-driven programming (§12.2). F To understand event, event source,
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
Chapter 7 A First Look at GUI Applications Layout Managers.
Chapter 8 Getting Started with Graphics Programming Graphics Class Hierarchy Graphics Class Hierarchy Frames Frames  Creating & centering frames, adding.
Object-Orientated Analysis, Design and Programming
Reference: COS240 Syllabus
Advanced Java Programming CSE 7345/5345/ NTU 531
Modern Programming Language Java
Chapter 13: Advanced GUIs and Graphics
Chapter 10 Getting Started with Graphics Programming
Chapter 13 Graphics.
Chapter 12 GUI Basics.
Chapter 13 Graphics.
Graphical User Interface
Presentation transcript:

Chapter 10 Getting Started with GUI Programming F GUI Class Hierarchy F Frames –Creating frames, centering frames, adding components to frames F Layout Managers –FlowLayout, GridLayout, BorderLayout F Drawing on Panels –The paintComponent method F Using Colors, Fonts, and Font Metrics F Drawing Geometric Figures –Lines, Rectangles, Ovals, Arcs, and Polygons F Event-Driven Programming –Event Source, Listener, Listener Interface

GUI Class Hierarchy (Swing)

JComponent

AWT (Optional)

Frames  Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications.  The Frame class can be used to create windows.  For Swing GUI programs, use JFrame class to create widows.

UI Components

Creating Frames Run import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } NOTE: You must have JDK 1.3 or higher to run the slides.

Centering Frames By default, a frame is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class. This method places the upper-left corner of a frame at location (x, y).

Centering Frames, cont. RunCenterFrame

Adding Components into a Frame // Add a button into the frame frame.getContentPane().add( new JButton("OK")); Run MyFrameWithComponents

NOTE The content pane is a subclass of Container. The statement in the preceding slide can be replaced by the following two lines: Container container = frame.getContentPane(); container.add(new JButton("OK")); You may wonder how a Container object is created. It is created when a JFrame object is created. A JFrame object uses the content pane to hold components in the frame.

Layout Managers F Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. F The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container.

Kinds of Layout Managers F FlowLayout (Chapter 10) F GridLayout (Chapter 10) F BorderLayout (Chapter 10)  CardLayout (Chapter 12) F GridBagLayout (Chapter 12)

Example 10.1 Testing the FlowLayout Manager The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started. ShowFlowLayoutRun

FlowLayout Constructors F public FlowLayout(int align, int hGap, int vGap) Constructs a new FlowLayout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances in pixel between components. F public FlowLayout(int alignment) Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical. F public FlowLayout() Constructs a new FlowLayout with a default center alignment and a default gap of five pixels for both horizontal and vertical.

Example 10.2 Testing the GridLayout Manager The GridLayout manager 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. ShowGridLayoutRun

GridLayout Constructors  public GridLayout(int rows, int columns) Constructs a new GridLayout with the specified number of rows and columns.  public GridLayout(int rows, int columns, int hGap, int vGap) Constructs a new GridLayout with the specified number of rows and columns, along with specified horizontal and vertical gaps between components.

Example 10.3 Testing the BorderLayout Manager The BorderLayout manager divides the container into five areas: East, South, West, North, and Center. Components are added to a BorderLayout by using the add method. ShowBorderLayout Run add(Component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER.

Example 10.3, cont. ShowBorderLayoutRun

Using Panels as Containers F Panels act as smaller containers for grouping user interface components.  It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel.

Example 10.4 Testing Panel This example uses panels to organize components. The program creates a user interface for a Microwave oven. TestPanelsRun

Drawing on Panels JPanel can be used to draw graphics (including text) and enable user interaction. To draw in a panel, you create a new class that extends JPanel and override the paintComponent method to tell the panel how to draw things. You can then display strings, draw geometric shapes, and view images on the panel.

Drawing on Panels, cont. public class DrawMessage extends JPanel { /** Main method */ public static void main(String[] args) { JFrame frame = new JFrame("DrawMessage"); frame.getContentPane().add(new DrawMessage()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); } /** Paint the message */ public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Welcome to Java!", 40, 40); }

Drawing on Panels, cont.

NOTE The Graphics class is an abstract class for displaying figures and images on the screen on different platforms. The Graphics class is implemented on the native platform in the JVM. When you use the paintComponent method to draw things on a graphics context g, this g is an instance of a concrete subclass of the abstract Graphics class for the specific platform. The Graphics class encapsulates the platform details and enables you to draw things uniformly without concerning specific platforms.

NOTE Whenever a component is displayed, a Graphics object is created for the component. The Swing components use the paintComponent method to draw things. The paintComponent method is automatically invoked to paint the graphics context when the component is first displayed or whenever the component needs to be redisplayed. Invoking super.paintComponent(g) is necessary to ensure that the viewing area is cleared before a new drawing is displayed.

NOTE To draw things, normally you create a subclass of JPanel and override its paintComponent method to tell the system how to draw. In fact, you can draw things on any GUI component.

The Color Class You 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);

Setting Colors You can use the following methods to set the component’s background and foreground colors: setBackground(Color c) setForeground(Color c) Example: setBackground(Color.yellow); setForeground(Color.red);

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

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]);

Setting Fonts public void paint(Graphics g) { Font myFont = new Font("Times", Font.BOLD, 16); g.setFont(myFont); g.drawString("Welcome to Java", 20, 40); //set a new font g.setFont(new Font("Courier", Font.BOLD+Font.ITALIC, 12)); g.drawString("Welcome to Java", 20, 70); }

The FontMetrics Class public void paint(Graphics g) { g.getFontMetrics(Font f); or g.getFontMetrics(); }

Get FontMetrics F public int getAscent() F public int getDescent() F public int getLeading() F public int getHeight() F public int stringWidth(String str)

Example 10.5 Using FontMetrics F Objective: Display “Welcome to Java” in SansSerif 20-point bold, centered in the frame. MessagePanel Run TestFontMetrics

Example 10.5, cont.

Drawing Geometric Figures F Drawing Lines F Drawing Rectangles F Drawing Ovals F Drawing Arcs F Drawing Polygons

Drawing Lines drawLine(x1, y1, x2, y2);

Drawing Rectangles F drawRect(x, y, w, h); F fillRect(x, y, w, h);

Drawing Rounded Rectangles F drawRoundRect(x, y, w, h, aw, ah); F fillRoundRect(x, y, w, h, aw, ah);

Drawing Ovals F drawOval(x, y, w, h); F fillOval(x, y, w, h);

Drawing Arcs F drawArc(x, y, w, h, angle1, angle2); F fillArc(x, y, w, h, angle1, angle2);

Drawing Polygons int[] x = {40, 70, 60, 45, 20}; int[] y = {20, 40, 80, 45, 60}; g.drawPolygon(x, y, x.length); g.fillPolygon(x, y, x.length);

Example 10.6 Drawing a Clock F Objective: Use drawing and trigonometric methods to draw a clock showing the specified hour, minute, and second in a frame. DisplayClock Run DrawClock

Drawing Clock xEnd = xCenter + handLength  sin(  ) yEnd = yCenter - handLength  cos(  ) Since there are sixty seconds in one minute, the angle for the second hand is second  (2  /60)

Drawing Clock, cont. xEnd = xCenter + handLength  sin(  ) yEnd = yCenter - handLength  cos(  ) The position of the minute hand is determined by the minute and second. The exact minute value comined with seconds is minute + second/60. For example, if the time is 3 minutes and 30 seconds. The total minutes are 3.5. Since there are sixty minutes in one hour, the angle for the minute hand is (minute + second/60)  (2  /60)

Drawing Clock, cont. xEnd = xCenter + handLength  sin(  ) yEnd = yCenter - handLength  cos(  ) Since one circle is divided into twelve hours, the angle for the hour hand is (hour + minute/60 + second/(60  60)))  (2  /12)

Event-Driven Programming F Procedural programming is executed in procedural order.  In event-driven programming, code is executed upon activation of events.

Events F An event can be defined as a type of signal to the program that something has happened. F The event is generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer.

Event Information  id : A number that identifies the event.  target : The source component upon which the event occurred.  arg : Additional information about the source components.  x, y coordinates : The mouse pointer location when a mouse movement event occurred.  clickCount : The number of consecutive clicks for the mouse events. For other events, it is zero.  when : The time stamp of the event.  key : The key that was pressed or released.

Event Classes

Selected User Actions SourceEvent Type User ActionObjectGenerated Clicked on a button JButtonActionEvent Changed text JTextComponentTextEvent Double-clicked on a list item JListActionEvent Selected or deselected an item JListItemEvent with a single click Selected or deselected an item JComboBoxItemEvent

The Delegation Model

Selected Event Handlers Event ClassListener InterfaceListener Methods (Handlers) ActionEventActionListeneractionPerformed(ActionEvent) ItemEventItemListeneritemStateChanged(ItemEvent) WindowEventWindowListenerwindowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) ContainerEventContainerListenercomponentAdded(ContainerEvent) componentRemoved(ContainerEvent)

Example 10.7 Handling Simple Action Events  Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked. TestActionEvent Run

Example 10.8 Handling Window Events TestWindowEvent Run  Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.

Example 10.9 M ultiple Listeners for a Single Source TestMultipleListener Run  Objective: This example modifies Example 10.7 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listner. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.