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

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

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

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

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

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

Chapter 12 GUI Basics

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

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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

user-friendly and easy to use.

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphical User Interfaces. Comp 152

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

Window Interfaces Using Swing Objects

Chapter 6: Graphical User Interfaces

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

2110: GUIS: Graphical User Interfaces

Java IDE Programming-I

Swing. By Iqtidar Ali

Window Interfaces Using Swing Objects

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

CS 251 Intermediate Programming GUIs: Components and Layout

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

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.

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

Chapter 12 Advanced GUIs and Graphics

Graphical User Interfaces in Java - SWING

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Part I: Learn Common Graphics Components

Packages: Putting Classes Together

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

Introduction. Introduction

CS111: PROGRAMMING LANGUAGE II

BASICS OF GRAPHICAL APPS

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

Java. GUI building with the AWT

Dr. Hikmat A. M. AbdelJaber

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

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

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Java Programming Lecture 6

2010 가을학기부산대학교정보컴퓨터공학부 OVERVIEW OF GUI PROGRAMMING

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

GUI in Java TalentHome Solutions

Lecture 18 Java Graphics and GUIs

Java: Graphical User Interfaces (GUI)

Systems Programming Graphical User Interfaces

Unit 6: Graphical User Interface

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

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

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

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

Programming graphics

Java Graphical User Interfaces

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

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

Top-Level Containers

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

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!

Summary Chapter 25 GUI Components: Part 2

CSE 331 Software Design & Implementation

Chapter 7: A First Look at GUI Applications

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

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

INTRODUCTION TO (GUIS)

Java 11 Swing with Eclipse Index

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Agenda. Container and Component

Basicsof. JavaGUI and SWING

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

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

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

Together, the appearance and how user interacts with the program are known as the program look and feel.

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

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

Java 1.9 Swing Index

Graphical User Interfaces in Java

Graphical User Interfaces

Object-Oriented Programming Design. Topic : User Interface Components with Swing GUI Part III

1.1 GUI. JFrame. import java.awt.*; import javax.swing.*; public class XXX extends JFrame { public XXX() { // XXX. init() main() public static

Java 11 Swing Index. Section Title Page

MIT AITI Swing Event Model Lecture 17

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

PIC 20A GUI with swing

Java 1.8 Swing with Eclipse Oxygen Index

Java 1.8 Swing with Eclipse Mars Index

Java 1.8 Swing with Eclipse Neon Index

Graphical interfaces & event-driven programming

Contents Chapter 1 Introduction to Programming and the Java Language

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Swing Programming Example Number 2

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

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

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Transcription:

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement User Interface components Buttons, radio buttons, text fields, etc Extends an earlier library: AWT Dimension Font LayoutManager 1 Classes in the java.awt package Heavyweight FontMetrics Object Color Panel Applet JApplet Graphics Component Container Window Frame JFrame * Dialog JDialog JComponent Swing Components in the javax.swing package JComponent and its subclasses: AbstractButton JMenuItem JButton JCheckBoxMenuItem JMenu JRadioButtonMenuItem JToggleButton JCheckBox JComponent JEditorPane JRadioButton JTextComponent JTextField JPasswordField JTextArea JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip JTree JTable JTableHeader - 1 - JInternalFrame JProgressBar JSpinner

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 2 of 12 Need a Container object in which to place UI components - will use JFrame. JFrame a window that cannot be put inside another window components can be added to a frame s content pane (getcontentpane() instance method) using method add First, a simple example: Create a window with a Label, TextField and 2 buttons, Hi and Exit. /** * Simple Java program displaying a window. */ import java.awt.container; import java.awt.flowlayout; import javax.swing.*; public class SimpleFrame extends JFrame { private JButton hi = new JButton("Hi"); private JButton exit = new JButton("Exit"); private JTextField tf = new JTextField(10); public SimpleFrame (){ // recall, the no arg constructor of superclas, // i.e. JFrame gets called here. this.setsize(450, 100); this.settitle("simple Frame example"); this.setlocation(300, 300); this.setdefaultcloseoperation(exit_on_close); // tell it how to lay out components this.setlayout(new FlowLayout()); // add components this.add(new JLabel("Enter your name")); this.add(tf); this.add(hi); this.add(exit); this.setvisible(true); public static void main(string[] args) { // instantiate the class, will display a window new SimpleFrame(); Common pitfalls: Don t forget to set a layout Don t forget to make the frame visible Otherwise the window will not show all components or may not show at all! - 2 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 3 of 12 Examples: some things that are commonly done: JLabel: JLabel l = new JLabel( Put text here ); l.settext( Change it here ); JTextFields: JTextField t1 = new JTextField(25); JTextField t2 = new JTextField( Balance, 20); t1.settext( Deposit ); // set content String s = t2.gettext(); // retrieve content t1.seteditable(false); // user can t change contents JTextArea: JTextArea a1 = new JTextArea(10, 25); // rows, cols JTextArea a2 = new JTextArea( list accounts:, 10, 25); a1.settext( account 1 ); // replace content a1.append( account 2 ); // append to content a2.append( account 1 ); // append to content a1.seteditable(false); // user can t change contents JList: Object [] oarray = ; JList l = new JList(oArray); Object o = l. getselectedvalue(); JRadioButton and ButtonGroups: JRadioButton add = new JRadioButton("Addition", true); JRadioButton subtract=new JRadioButton("Subtraction", false); The isselected() method returns true if the RadioButton is selected, and false otherwise. Add a component of type ButtonGroup to ensure to groups radio buttons so only 1 can be selected at any given time: ButtonGroup operations = new ButtonGroup(); operations.add(add); operations.add(subtract); A Visual Guide to Swing Components: http://drootr.com/apcs/tutorial/ui/features/components.html - 3 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 4 of 12 Event Handling An event can be defined as a type of signal to the program that something has happened. The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, e.g. a timer event. Source Event Type User Action Object Generated Click a button JButton ActionEvent Click a check box JCheckBox ItemEvent, ActionEvent Click a radio button JRadioButton ItemEvent, ActionEvent Press return on a text field JTextField ActionEvent Select a new item JComboBox ItemEvent, ActionEvent Window opened, closed, etc. Window WindowEvent Mouse pressed, released, etc. Component MouseEvent Mouse moved, dragged. Component MouseMotionEvent Key released, pressed, etc. Component KeyEvent User input through UI Components is processed via event-handling mechanism: Program waits for events to occur and then responds Firing an event when a source object generates an event Listener object that receives a notification of an event occurring. Event handler method that gets called in response to an event Listener Object must implement the appropriate Event handler method, specified by an in an appropriate listener interface (e.g. ActionListener, ItemListener, MouseEventListener, etc..) An event object contains whatever properties are pertinent to the event (the source component that fired the event, the time, etc ) You can identify the source object of the event using the getsource() instance method in the EventObject class Handling ActionEvents (generated by button-clicks, presses of Enter in TextArea, etc..) Register receiver (e.g. MathQuiz) as the listener object for the Button (or other source object). source.addactionlistener(receiver); The listener object (e.g.mathquiz ) must implement the ActionListener interface, i.e. provide definition of method public void actionperformed(actionevent e) Simple example: extending the SimpleFrame to react to ActionEvents - 4 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 5 of 12 /** * Simple Java program displaying a window.reacts to ActionEvents */ import java.awt.*; import javax.swing.*; public class SimpleFrame extends JFrame implements ActionListener { private JButton hi = new JButton("Hi"); private JButton exit = new JButton("Exit"); private JTextField tf = new JTextField(10); public SimpleFrame (){ // recall, the no arg constructor of superclas, // i.e. JFrame gets called here. this.setsize(450, 100); this.settitle("simple Action Listener"); this.setlocation(300, 300); this.setdefaultcloseoperation(exit_on_close); // tell it how to lay out components this.setlayout(new FlowLayout()); // add components this.add(new JLabel("Enter your name")); this.add(tf);this.add(hi); this.add(exit); // register this as a listener to action events // from the following components tf.addactionlistener(this); hi.addactionlistener(this); exit.addactionlistener(this); this.setvisible(true); /** Method required by the ActionListener interface * Is passed in an event as a parameter. * Performs an action based on the source of event. */ public void actionperformed(actionevent event) { if (event.getsource() == hi){ // hi button was pressed System.out.println("Hi, " + tf.gettext() + "!"); else if (event.getsource() == exit) { // exit button was pressed System.out.println("Bye, " + tf.gettext() + "!"); System.exit(0); else if (event.getsource() == tf) { // user pressed enter in the text field System.out.println("Nice to meet you, " + tf.gettext() + "!"); public static void main(string[] args) { // instantiate the class, will display a window new SimpleFrame(); - 5 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 6 of 12 Problem: create a simple graphical MathQuiz program that displays random problems, allows user to enter their answer, checks correctness. JRadioButton JLabel JButton JTextBox JTextArea /** MathQuizWindow.java The class implements a window with GUI components Shows how to add components to a frame. */ import java.awt.*; // helper classes like Color, LayoutManager, etc. import javax.swing.*; // library of components public class MathQuizWindow extends JFrame { // Define instance vars, simultaneously initializing them // by calling an appropriate constructor private JLabel label = new JLabel("Enter answer"); private JLabel lquestion = new JLabel(" a problem "); // to let user enter answer private JTextField tfanswer = new JTextField(15); cols //to show if correct or not, and correct answer if wrong private JTextArea answers = new JTextArea(2,20); //2 rows, 20 private JButton question = new JButton("Get question"); private JButton answer = new JButton("Submit"); private JButton exit = new JButton("Exit"); private JRadioButton add = new JRadioButton("Addition", true); private JRadioButton subtract = new JRadioButton("Subtraction", false); - 6 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 7 of 12 /** Constructor */ public MathQuizWindow (){ // recall: default superclass no-args // constructor is called here (i.e. JFrame ()) // creates a frame, initially invisible // set a few properties of the frame window this.setsize(250, 270); this.settitle("simple Math Quiz"); this.setdefaultcloseoperation(exit_on_close); //TO add the components to the container pane of the frame // 2. tell the frame how to arrange components: // using FlowLayout, componentes arranged around the center // by default this.setlayout(new FlowLayout()); // add radio buttons this.add(add); this.add(subtract); // Group radio buttons together in a group // to ensure *single* selection at any time: ButtonGroup operations = new ButtonGroup(); operations.add(add); operations.add(subtract); // add other components this.add(question); this.add(lquestion); lquestion.setforeground(color.blue); this.add(label); this.add(tfanswer);this.add(answer); this.add(answers); this.add(exit); this.setvisible(true); public static void main(string[] args) { // Create an instance of the Math Quiz new MathQuizWindow (); Result: A frame that contains GUI components, but doesn t do anything in response - 7 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 8 of 12 If window is resized, components may be repositions relatively to each other because FlowLayout was used. To ensure relative positioning is the same use LayoutManager objects. Example: add functionality to the MathQuiz class on pages 4-5 to 1. Display a problem (see class Problem) in the TextField tfquestion when the Get Question button is pressed, according to the operation selected with the radio buttons. At the same time clear tfanswer and set cursor there. 2. Read contents of TextField tfanswer when the answer button is pressed, at the same time, display if answer was correct in the text area answers. /** Class Problem. Creates an arithmetical problem */ public class Problem { private int op1; private int op2; private char operator; // generate random operators public Problem(char operator){ this.op1 = 1+(int)(20 * Math.random()); //between 1 and 20 this.op2 = 1+(int)(20 * Math.random()); //between 1 and 20 this.operator = operator; // generate math problem public int getanswer(){ int answer; if (this.operator == '+') answer = op1 + op2; else if (this.operator == '-') answer = op1 - op2; else - 8 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 9 of 12 answer = op1 * op2; return answer; public String tostring(){ return op1 + " " + operator + " " + op2 + " =??"; public static void main (String [] args){ Problem p1 = new Problem('+'); System.out.println (p1); System.out.println (p1.getanswer()); Layout Managers Every container (JFrame, JPanel, JDialog) contains a LayoutManager object that determines relative positioning and size of components inside a container. Layout managers are assigned to a container using the setlayout(layoutmanager) method of a container. E.g. of LayoutManagers are FlowLayout, BorderLayout, GridLayout, GridBagLayout, and more classes. Useful tutoorilal on which to use and how: http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html BorderLayout manager arranges components into five areas: East, South, West, North, and Center. Components are added to a BorderLayout by using the add method with an appropriate constraint add(component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER. GridLayout manager arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor. Cosntructors: public GridLayout(int rows, int columns) - 9 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 10 of 12 Useful technique: 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. The components are placed in the grid from left to right starting with the first row, then the second, and so on. Can place components to panels (objects of type JPanel).You can also place panels in a panel. Then add those panels to the frame s (JFrame) content pane. Frame s contentpane Has BorderLayout questionpanel with 2 by 2 GridLayout answerpanel with FlowLayout, centered. - 10 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 11 of 12 /** The class implements a window with GUI components Shows how to add components in panels, using different layout managers. */ import java.awt.*; import javax.swing.*; // library of components public class MathQuizWindowWithPanels extends JFrame{ // Define instance vars, simultaneously initializing them private JLabel label = new JLabel("Enter answer"); private JLabel lquestion = new JLabel(" a problem "); // to let user enter answer private JTextField tfanswer = new JTextField(15); //to show if correct or not, and correct answer if wrong private JTextArea answers = new JTextArea (2, 20); private JButton question = new JButton("Get question"); private JButton answer = new JButton("Submit"); private JButton exit = new JButton("Exit"); private JRadioButton add = new JRadioButton("Addition", true); private JRadioButton subtract=new JRadioButton("Subtraction", false); /** Constructor */ public MathQuizWindowWithPanels (){ // recall: default superclass no-args // constructor is called here // creates a frame, initially invisible // set a few properties of the window this.setsize(350, 200); this.settitle("simple Math Quiz"); //TO add the components to the container pane of the frame // 1. get the content pane of the JFrame Container contentpane = this.getcontentpane(); // 2. tell the pane how to arrange components: //using BorderLayout with specified horiz. and vert.spacing contentpane.setlayout(new BorderLayout(5, 10)); JPanel questionpanel = createquestionpanel(); contentpane.add(questionpanel, BorderLayout.NORTH); JPanel answerpanel = createanswerpanel(); contentpane.add(answerpanel, BorderLayout.CENTER); contentpane.add(exit, BorderLayout.SOUTH); this.setvisible(true); - 11 -

Handout 12 CS603 Object-Oriented Programming Fall 15 Page 12 of 12 /** Creates a panel with question-related componenets */ private JPanel createquestionpanel(){ // create a panel JPanel qpanel = new JPanel(); // tell it to arrange components in 2 by 2 grid qpanel.setlayout(new GridLayout(2,2, 10, 10)); // add components to the panel in order left->right // top -> bottom // add radio buttons qpanel.add(add); qpanel.add(subtract); qpanel.add(question); lquestion.setforeground(color.blue); qpanel.add(lquestion); // Group radio buttons together in a group // to ensure *single* selection at any time: ButtonGroup operations = new ButtonGroup(); operations.add(add); operations.add(subtract); return qpanel; /** Creates a panel with answer-related componenets */ private JPanel createanswerpanel(){ // create a panel JPanel apanel = new JPanel(); apanel.setlayout(new FlowLayout()); apanel.add(label); apanel.add(tfanswer); apanel.add(answer); apanel.add (answers); return apanel; public static void main(string[] args) { // Create an instance of the Math Quiz new MathQuizWindowWithPanels (); - 12 -