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

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!

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

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

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

PIC 20A GUI with swing

Graphical User Interfaces. Comp 152

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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

GUI in Java TalentHome Solutions

Graphical User Interfaces in Java - SWING

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects

Agenda. Container and Component

Java. GUI building with the AWT

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

AP CS Unit 11: Graphics and Events

User interfaces and Swing

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

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

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

CSIS 10A Assignment 7 SOLUTIONS

Systems Programming Graphical User Interfaces

MIT AITI Swing Event Model Lecture 17

Graphic User Interfaces. - GUI concepts - Swing - AWT

H212 Introduction to Software Systems Honors

COMP16121 Sample Code Lecture 1

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

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

Introduction. Introduction

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

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

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Part I: Learn Common Graphics Components

SampleApp.java. Page 1

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

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Java, Swing, and Eclipse: The Calculator Lab.

JAVA NOTES GRAPHICAL USER INTERFACES

Graphical User Interfaces in Java

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

Lecture 9. Lecture

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CSC 161 SPRING 17 LAB 2-1 BORDERLAYOUT, GRIDLAYOUT, AND EVENT HANDLING

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

Dr. Hikmat A. M. AbdelJaber

Graphical User Interface (GUI)

CS11 Java. Fall Lecture 4

Java Programming Lecture 6

Window Interfaces Using Swing. Chapter 12

Building Java Programs Bonus Slides

Swing from A to Z Some Simple Components. Preface

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

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

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

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

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

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

CS 251 Intermediate Programming GUIs: Components and Layout

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

Lecture 5: Java Graphics

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Class 16: The Swing Event Model

Basicsof. JavaGUI and SWING

Swing - JButton. Adding buttons to the main window

FirstSwingFrame.java Page 1 of 1

Object Oriented Design & Patterns. Part 1

Programming Language Concepts: Lecture 8

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

Graphical User Interfaces (GUIs)

CS11 Java. Fall Lecture 3

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

CHAPTER 2. Java Overview

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

ITEC 120 4/14/11. Review. Need. Objectives. GUI basics JFrame JPanel JLabel, JButton, JTextField Layout managers. Lecture 38 GUI Interactivity

Example: Building a Java GUI

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

SINGLE EVENT HANDLING

Example: Building a Java GUI

encompass a group of features for building Graphical User Interfaces (GUI).

Chapter 7: A First Look at GUI Applications

BASICS OF GRAPHICAL APPS

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

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

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

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

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

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

Lecture 3: Java Graphics & Events

CS108, Stanford Handout #22. Thread 3 GUI

CS 11 java track: lecture 3

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

CMP 326 Midterm Fall 2015

To gain experience using GUI components and listeners.

2IS45 Programming

Transcription:

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

Lecture Outline 1. Swing components 2. Building a GUI 3. Animating the GUI 2

Swing A collection of classes of GUI components Contains classes to implement windows, buttons, menus etc. Uses event listener model to attach handlers to the UI components Huge and complex collection of packages Augments/replaces older AWT 3

Basic Workflow Create a window to hold your entire GUI Arrange UI components inside the window Add individual components, or Group components into containers and add them to the window Attach handler(s) to each UI component to handle the events they generate 4

The main window The class javax.swing.jframe is used as the outermost window in a Swing GUI java.lang.object java.awt.component java.awt.container java.awt.window java.awt.frame javax.swing.jframe 5

Extend JFrame import javax.swing.*; import java.awt.*; public class MyGUI extends Jframe { // Declare UI components } public MyGUI(String title) { super(title); // Add UI components pack(); setvisible(true); } 6

Constructor First, call the superclass constructor Then add any UI components (none yet) Then pack the window - this lays out the UI components Make the window visible Currently the window appears, but does nothing at all! 7

Getting rid of the window What should happen if the user closes the window? For the main application, closing should terminate the program setdefaultcloseoperation(jframe.exit_on_close);! Other options are DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE 8

UI Components Many UI components, including JLabel - information labels JButton - clickable buttons JTextField - text entry fields Organize these with A layout manager, and JPanel to group components 9

An RPN Calculator 9234.0134 A JLabel for the output 7 8 9 * 4 5 6 + 1 2 3 - Lots of JButtons A JPanel to organise the buttons 0. E / The outside JFrame 10

Layout Managers The contents of any container are laid out according to a specified layout manager java.awt.flowlayout - free flowing java.awt.borderlayout - five different areas (center, north, south, east, west) java.awt.gridlayout - rectangular grid java.awt.gridbaglayout - complex grid 11

Which layouts? The overall JFrame will have a BorderLayout with a JLabel in the North position and the button panel in the Center position In the constructor for MyGUI we add setlayout(new BorderLayout()); 12

Add the display label In the instance variables private JLabel display; In the constructor display = new JLabel ( 0,SwingConstants.RIGHT); add(display,borderlayout.north); 13

Declare the buttons Extra instance variables private JButton[] numbers = new JButton[10];! private JButton add;! private JButton sub;! private JButton mul;! private JButton div;! private JButton decimal;! private JButton enter; 14

Create the buttons!for (int i=0; i<10; i++)!!numbers[i] = new JButton(String.valueOf(i));!!decimal = new JButton(".");!!add = new JButton("+");!!sub = new JButton("-");!!div = new JButton("/");!!mul = new JButton("*");!!enter = new JButton("Enter"); 15

Create the button panel JPanel buttonpanel = new JPanel();! buttonpanel.setlayout(new GridLayout(4,4));! 16

Add buttons to the panel.. buttonpanel.add(numbers[7]);! buttonpanel.add(numbers[8]);! buttonpanel.add(numbers[9]);! buttonpanel.add(mul);!! Each new component occupies the next empty grid position working row by row.. buttonpanel.add(numbers[0]);! buttonpanel.add(decimal);! buttonpanel.add(enter);! buttonpanel.add(div); 17

Add panel to main JFrame add(buttonpanel,borderlayout.center); 18

Ugly GUI This is pretty ugly at the moment - it can be beautified with borders, background colours, images etc. However this is beyond our immediate scope! 19

Adding logic Now we need to add the logic - to actually respond to button clicks etc. The GUI will be responsible for the entry and display of the numbers, while an existing class will manage the arithmetic 20

Make the GUI an ActionListener Declare that the class implements the java.awt.event.actionlistener interface import java.awt.event.*; public class MyGUI extends JFrame implements ActionListener { // previous code goes here } 21

Register with all the buttons While the GUI constructs the buttons, it should register itself with them for (int i=0; i<10; i++) {!!numbers[i] = new JButton(String.valueOf (i));!!numbers[i].addactionlistener(this);! }! decimal = new JButton(".");! decimal.addactionlistener(this); 22

A required method To claim to be an ActionListener, the GUI object must implement void actionperformed(actionevent e) Whenever an action occurs on a UI component (e.g. a JButton) the button calls this method of all of its registered listeners 23

What should it do? Every time the user clicks a button, the button will call the actionperformed method of the GUI object The GUI object therefore needs to Work out which button was pushed Do the appropriate thing 24

Which button was pushed? The ActionEvent object contains this information and it can be obtained using!e.getactioncommand() Each button has an action command The default action command is simply the label on the button, or (Better) the programmer can set the action command on construction of the button 25

What should our GUI do? public void actionperformed(actionevent e) {! String s = e.getactioncommand();! switch (s.charat(0)) {! case '+':! case '-':! case '*':! case '/': dooperation(s);! break;! case 'E': doenter(s);! break;! default: processdigitordecimal(s);! }! }! }! 26

Processing digits Extract the currently displayed string from the JLabel that is the display String curr = display.gettext(); Perform some processing to decide how the display should be updated, and then set some new text display.settext(update); 27

Processing logic Logic is surprisingly involved! If display at maximum length, do nothing If button pressed was. and display already contains a. do nothing If display currently 0 If button pushed was a digit then replace the 0 If button pushed was. then append it to the 0 Otherwise Append the string to the current display 28

Regular Expressions A regular expression, often called a pattern, is an expression that describes a set of strings. The IEEE POSIX Basic Regular Expressions (BRE) standard can be used to denote regular expressions 29

RE examples [ab6] matches a or b or 6 [a-z] matches any lower case letter from a to z [a-z]* matches any sequence of zero or more lower case letters [a]*b[0-9]* matches aaab04324324, b, ab999 etc a-[c]* matches a followed by - followed by zero or more c characters 30

String.matches public boolean matches(string regex) Tells whether or not this string matches the given regular expression. Regular expressions in Java use the Posix standard 31

A simple test program for experimenting with REs String s = "aaabbb"; if (s.matches("[a]*[b]*")) { System.out.println("matches"); } else { System.out.println( does not match"); } 32