Part 3: Graphical User Interface (GUI) & Java Applets

Similar documents
Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Chapter 12 GUI Basics

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Programming graphics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Introduction to the JAVA UI classes Advanced HCI IAT351

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Graphic User Interfaces. - GUI concepts - Swing - AWT

Chapter 12 Advanced GUIs and Graphics

Java Programming Lecture 6

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Graphical User Interface (GUI)

CS 251 Intermediate Programming GUIs: Components and Layout

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Graphical User Interfaces. Comp 152

Window Interfaces Using Swing Objects

Swing. By Iqtidar Ali

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Window Interfaces Using Swing Objects

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

1.00 Lecture 14. Lecture Preview

Starting Out with Java: From Control Structures Through Objects Sixth Edition

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Learn Java Programming, Dr.Hashamdar. Getting Started with GUI Programming

Java IDE Programming-I

Lecture 18 Java Graphics and GUIs

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Class 14: Introduction to the Swing Toolkit

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

JAVA NOTES GRAPHICAL USER INTERFACES

Chapter 13. Applets and HTML. HTML Applets. Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

Packages: Putting Classes Together

Chapter 12 GUI Basics. Motivations. The design of the API for Java GUI programming

G51PRG: Introduction to Programming Second semester Applets and graphics

Part I: Learn Common Graphics Components

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Graphical User Interfaces (GUIs)

Summary Chapter 25 GUI Components: Part 2

CSE 331 Software Design & Implementation

ASSIGNMENT NO 14. Objectives: To learn and demonstrated use of applet and swing components

Graphics User Defined Forms, Part I

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Unit 6: Graphical User Interface

AP CS Unit 11: Graphics and Events

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Graphical User Interfaces

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Event Driven Programming

GUI Forms and Events, Part II

Java. GUI building with the AWT

Class 16: The Swing Event Model

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Graphical User Interface (GUI)

INTRODUCTION TO (GUIS)

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

Introduction. Introduction

Example 3-1. Password Validation

Lecture 5: Java Graphics

Today. cisc3120-fall2012-parsons-lectiii.3 2

Graphical User Interface (GUI)

DM503 Programming B. Peter Schneider-Kamp.

Graphical User Interface (GUI) and Object- Oriented Design (OOD)

Sri Vidya College of Engineering & Technology

Basicsof. JavaGUI and SWING

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

JAVA NOTES GRAPHICAL USER INTERFACES

2110: GUIS: Graphical User Interfaces

Dr. Hikmat A. M. AbdelJaber

User interfaces and Swing

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Unit 7: Event driven programming

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

BASICS OF GRAPHICAL APPS

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Chapter 6: Graphical User Interfaces

Java: Graphical User Interfaces (GUI)

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

Systems Programming Graphical User Interfaces

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

Announcements. Introduction. Lecture 18 Java Graphics and GUIs. Announcements. CSE 331 Software Design and Implementation

Introduction p. 1 JFC Architecture p. 5 Introduction to JFC p. 7 The JFC 1.2 Extension p. 8 Swing p. 9 Drag and Drop p. 16 Accessibility p.

CSC 1214: Object-Oriented Programming

Java - Applets. public class Buttons extends Applet implements ActionListener

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

Graphical interfaces & event-driven programming

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Transcription:

1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ Check Box ƒ Combo Box ƒ Menu ƒ Dialog Java Applets (in comparison with Java Applications) EE905-GUI-2

2 7KH*UDSKLFV3DFNDJHV Originally, you would program graphics in Java using the AWT (Abstract Window Toolkit) - java.awt. The AWT provided (and still provides) cross-platform graphics support using the window and graphics functions provided by the various platforms, but for reasons you ll find in the textbooks, it s not the ideal way to do it. The later toolkit, and the one we ll be using, is called Swing - javax.swing. It does not rely on the platform s own libraries except for the most basic functions, but it still allows applications to be given a platform s look and feel. Swing does not replace the whole of the AWT functionality, so we ll generally be using classes from both in our programs. EE905-GUI-3 Creating a Window EE905-GUI-4

3 &UHDWLQJD:LQGRZ To use graphics, the first thing we need is a window to draw in. Here s a simple program that will create a window on the display: SimpleFrame.java Compile and Execution javac SimpleFrame.java java SimpleFrame Live Demo EE905-GUI-5 7KHSimpleFrame &ODVV class SimpleFrame extends JFrame { public SimpleFrame() { settitle("simpleframe"); setsize(300, 200); } This code defines a class called SimpleFrame, which is an extension of (i.e., inherits from) the JFrame class provided by Swing. The JFrame class is the standard class that provides a window. The method publicsimpleframe() is the constructor for the new class. It sets the title (displayed in the title bar of the window) and it sets the initial size of the window. You don t have to set the title, but you must set the size. Otherwise you get the JFrame s default size, which is zero by zero pixels and therefore not very useful. EE905-GUI-6

4 7KHmain 0HWKRG public static void main(string[] args) { SimpleFrame frame = new SimpleFrame(); frame.show(); } The main() method let us run SimpleFrame as a console application. It creates a new SimpleFrame object, and calls the object s show() method to display the window. New windows are not displayed until the show() method is called. This is so that you can create them and then draw in them before the user sees them. Then the main() method exits. You might expect this to terminate the program, but it doesn t. The window is left in control. EE905-GUI-7 &ORVLQJWKH:LQGRZ To make the program terminate, the obvious thing to do is to click the window s close box. But this doesn t work! The window does go away, but the program is still running - as you ll see from the absence of a Linux prompt in the console window. To make the program stop, you have to kill it by typing Control-C. Let s fix that... EE905-GUI-8

5 4XLWWLQJWKH3URJUDP The reason that the program doesn t quit when you close the window is that you don t always want it to. Your program might have several windows, for example, and it s unlikely that you d want the program to stop if you closed just one of them. Therefore, by default, windows can be closed and will go away, but the program will not stop. To make the window closure terminate the program, add this line in main() before the call to frame.show(). frame.setdefaultcloseoperation(jframe.exit_on_close); EE905-GUI-9 *LYLQJmain() LWV2ZQ&ODVV In the previous example, we put the main() method into the frame class. This works, but it s not the most natural way to do it because the frame class is not main() s natural home. (If there were many frames, which one would you put main() in?) Here s the program so far, but rearranged so that there s a top class to represent the program as well as the SimpleFrame class to represent the frame. See Graphics01.java in supplement. EE905-GUI-10

6 Panels EE905-GUI-11 $GG7ZR%XWWRQVLQWR:LQGRZ JPanel pane = new JPanel(); JButton button1 = new JButton("Click Me!"); pane.add(button1); JButton button2 = new JButton("Click Me Too!"); pane.add(button2); frame.getcontentpane().add(pane); (refer to Graphics02.java ) Create a new JPanel object A JPanel is a rectangular container for other graphics objects (widgets) Widgets added to a JPanel will be packed left to right and then top to bottom, like words in a paragraph Create two buttons, adding them to the JPanel. Add the JPanel to the frame object. EE905-GUI-12

7 )UDPHDQG3DQHO3DFNGLIIHUHQWO\ If we had added the buttons directly to the frame, the two buttons are still both there, but each has been made to be the full size of the window and the second one has been placed on top of the first. Demonstrate the difference. (refer to: Graphics03.java) That s why we use the JPanel to contain the buttons, and then pack just the JPanel into the frame. The JPanel s (default) layout method is called flow layout. EE905-GUI-13 )UDPHV8VH%RUGHU/D\RXW Actually, frames do some layout: by default, they use border layout. There are five areas: NORTH, SOUTH, EAST, WEST and CENTER. If you don t specify which area to put a widget in, it goes into the CENTER area (which is what has happened in the examples so far). If you put more than one widget into the same area, only the last one is visible (as we have seen). The following code adds a text label in the SOUTH area, with our twobutton JPanel still being placed in the CENTER area. (refer to Graphics04.java) JLabel label = new JLabel("Hi there!"); frame.getcontentpane().add(label,borderlayout.south); EE905-GUI-14

8 Event Handling EE905-GUI-15 (YHQWV An Event is an object in Java - a chunk of data stored in memory. One is created every time a button is clicked (or anything else happens, for that matter). To make your program respond to an event, you have to declare a listener object, which will contain a method that gets executed in response to the creation of the Event. EE905-GUI-16

9 /LVWHQHU Any object can be a listener object, provided you give its class two specific features: ƒ You must declare the class as one that implements ActionListener. ƒ You must declare a method within the class, of this form: public void actionperformed(actionevent event){... } The method name must be actionperformed; you can t just have any name of your choice. The following code adds some very minimal code to respond to a button click on the first button. (Refer to Graphics5.java) import java.awt.event.*; button1.addactionlistener(new Action()); class Action implements ActionListener { public void actionperformed(actionevent event) { Graphics05.label.setText("Thanks!"); } } EE905-GUI-17 $QRWKHUZD\WRJHW$SSOLFDWLRQWRHQG Refer to CloseableFrame.java in the supplement addwindowlistener(new WindowAdapter() { public void windowclosing(windowevent e) { System.exit(0); } }); EE905-GUI-18

10 )RQW Font class Five logical font names: ƒ SansSerif, Serif, Monospaced, Dialog, DialogInput System specific fonts available Font styles: ƒ Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD+Font.ITALIC Font sansb14 = new Font("SansSerif", Font.BOLD, 14); g.setfont(sansb14); EE905-GUI-19 &RORXU Color class Provides 13 standard colours e.g.: ƒ Color.black, Color.white, Color.red, Color.green, etc. Colours can also be defined by (red, green, blue) mix. e.g.: ƒ Color dullbluegreen = new Color(0, 128, 128); System colors can be used for portability, e.g.: ƒ SystemColor.window - background for windows ƒ SystemColor.windowBorder - Colour of window border frame ƒ SystemColor.windowText - Text colour inside windows Can use these colors to set e.g. current drawing colour: ƒ g.setcolor(color.red); or frame background: ƒ f.setbackground(systemcolor.window); EE905-GUI-20

1 6KDSH Within the paintcomponent() of a JPanel, use the supplied Graphics object g to draw Vast collection of methods, e.g.: drawstring(string str, int x, int y) drawline(int x1, int y1, int x2, int y2) drawpolygon(polygon p) fillpolygon(polygon p) Possible to draw images, but this is complicated by Java s support for downloading images across the network: see Image, Toolkit and MediaTracker classes EE905-GUI-21 (YHQW+DQGOLQJ([DPSOHV Live demo on ButtonFrame.java Live demo on MouseFrame.java EE905-GUI-22

12 Swing GUI Components EE905-GUI-23 9DVW6ZLQJ&RPSRQHQWV Vast array of GUI components: see Swing API (1.4) A visual index to the Swing component: here Including (as early as Swing 1.0.3) : ƒ JButton, JCheckbox, JCheckBoxMenuItem, JComboBox, JDialog, JEditorPane, JFileChooser, JLabel, JList, JMenu, JMenuBar, JMenuItem, JOptionPane, JPanel, JPasswordField, JPopupMenu, JProgressBar, JRadioButton, JRadioButtonMenuItem, JScrollBar, JScrollPane, JSlider, JTextArea, JTextField, JToolBar If these aren t enough, try e.g. Gamelan (http://www.developer.com/java/) to download additional contributed components Note: there are more components in later versions of Swing EE905-GUI-24

13 /D\RXW0DQDJHPHQW Every container has a layout manager. Java provides several ways to layout components automatically ƒ FlowLayout : Arranges components in a left-to-right flow, much like lines of text in a paragraph (default for JPanel ) ƒ BorderLayout : Lays out a container, arranging and resizing its components to fit in five regions: North, South, East, West, and Center (default for JFrame ) ƒ GridLayout : Lays out a container s components in a rectangular grid ƒ GridBagLayout : Flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size: tricky! Several others, plus write your own! C:\j2sdk1.4.0\tutorials\uiswing\mini\layout.html Layout Management Example: Calculator.java EE905-GUI-25 0RUH([DPSOHV See supplement Text Input: TextEditFrame.java Check Box: CheckBoxFrame.java Combo Box: ComboBoxFrame.java Menu: MenuFrame.java Dialog: DialogFrame.java EE905-GUI-26

14 Java Applets EE905-GUI-27 %DVLFVRI-DYD$SSOHWV An applet is a special kind of Java program that a Java-enabled browser can download from the internet and then run. Motivation behind applets: users would be freed from the hassles of installing software, and that they could access their software from any Java-enabled computer or device with an internet connection. Applets are embedded inside HTML page. The browser retrieves the class files from the internet (or from a directory on the user s machine) and automatically runs the applet. EE905-GUI-28

15 $Q([DPSOH$SSOHW Applications ƒ Main method: main() ƒ Example: Hello.java again Applets ƒ Example: HelloApplet.java ( HelloApplet.html ) ƒ Example: HelloApplet2.java ( HelloApplet2.html) Comparison of two by code analysis EE905-GUI-29 0DLQ0HWKRGVRIApplet &ODVV init(): Initialise applet Used for whatever initialization is needed for the applet. It works much like a constructor It is automatically called by the system when Java launches the applet for the first time. start(): Start or restart applet It is automatically called after Java calls the init method. paint(): Draw applet stop() : Stop applet It is automatically called when the user moves off the page on which the applet sits. destroy() : Release applet resources It is only called when the browser shuts down normally. Please refer to JDK API documentations EE905-GUI-30

16 6HFXULW\&RQFHUQVIRU$SSOHWV Applets (unlike applications) are restricted in what they can do. The applet security manager throws a SecurityException whenever an applet attempts to violate one of the access rules. Applets can normally do the following things: Showing images and playing sounds Getting keystrokes and mouse clicks from the user Sending user input back to the host from which they were loaded The restricted execution environment for applets is often called the sandbox. Applets playing in the sandbox cannot alter the user s system or spy on it. Be noted that applets are interpreted by JVM rather than CPU. Signed applets EE905-GUI-31 5XQ\RXU$SSOHWV To execute the applet, the following two steps need to be carried out: ƒ Compile your source files into class files ƒ Create an HTML file that tells the browser which class file to load first and how to size the applet. Before viewing the applet in a browser, you can test it in the applet viewer. ƒ at command line type in appletviewer followed by url) ƒ ƒ However, it shows you only the applet, not the surrounding HTML text And if an HTML file contains multiple applets, the applet viewer pops up multiple windows. To properly view the applet, you need a Java 2 enabled browsers. If the applet doesn t show up, your browser uses its built-in virtual machine, and you need to configure it to use the Java Plug-in instead. EE905-GUI-32

17 &RQYHUWLQJ$SSOLFDWLRQVWR$SSOHWV Easy and essentially all of the user interface code can stay the same. Steps: ƒ Make an HTML page with the appropriate tag to load the applet code. ƒ Supply a subclass of the JApplet class. Make this class public. ƒ Eliminate the main method in the application. Do not construct a frame window for the application (because applet is displayed inside browser). ƒ Move any initialization code from the frame window constructor to the init method of the applet. ƒ Remove the call to setsize for applets, sizing is done by HTML file. ƒ Remove the call to setdefaultcloseoperation. Applets terminate when the browser exits. ƒ If the application calls settitle, remove it because applets don t have title bar (but you can title the web page by using the HTML title tag). ƒ Don t call show. Applets are displayed automatically. Example: refer to Calculator.java and CalculatorApplet.java EE905-GUI-33 3DVVLQJ,QIRUPDWLRQWR$SSOHWV Applets can use parameters that are embedded in the HTML file. This is done via the HTML tag called param along with attributes. <applet code= AppletA.class width=200 height=200> <param name= font value= Arial /> <param name= size value= 20 /> </applet> public class AppletA extends JApplet { public void init() { String fontname = getparameter ( font ); int fontsize = Integer.parseInt(getParameter( size )); End of Part 3 EE905-GUI-34