Example: Building a Java GUI

Similar documents
Example: Building a Java GUI

Multi-Threading : Doing Things in Parallel

Multi-Threading : Doing Things in Parallel

PIC 20A GUI with swing

CS 251 Intermediate Programming GUIs: Components and Layout

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

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

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

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!

Agenda. Container and Component

Lecture 5: Java Graphics

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

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

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

AP CS Unit 11: Graphics and Events

Window Interfaces Using Swing. Chapter 12

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

COMP16121 Sample Code Lecture 1

Lecture 3: Java Graphics & Events

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

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

CS 251 Intermediate Programming GUIs: Event Listeners

Java Programming Lecture 6

SampleApp.java. Page 1

Introduction. Introduction

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

Java. GUI building with the AWT

Final Exam CS 251, Intermediate Programming December 13, 2017

AP CS Unit 12: Drawing and Mouse Events

Dr. Hikmat A. M. AbdelJaber

Window Interfaces Using Swing Objects

Java Interfaces Part 1 - Events Version 1.1

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

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

Graphic User Interfaces. - GUI concepts - Swing - AWT

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Window Interfaces Using Swing Objects

Graphical User Interfaces. Comp 152

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

User interfaces and Swing

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

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

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

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

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921

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

APPENDIX. public void cekroot() { System.out.println("nilai root : "+root.data); }

To gain experience using GUI components and listeners.

Graphical User Interfaces in Java - SWING

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

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946

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

More about GUIs GEEN163

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

CHAPTER 2. Java Overview

Graphical User Interfaces (GUIs)

PART 22. Java GUI Library SWT GUI Library SWING GUI Library Swing First Program

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:

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

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

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

G51PRG: Introduction to Programming Second semester Applets and graphics

ming 3 Resize the Size to [700, 500]. Note that the background containers in the program code: reference the then under () { 153, 255, 0 ) );

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

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

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

Building Java Programs Bonus Slides

2IS45 Programming

Part I: Learn Common Graphics Components

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

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

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

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

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Class 16: The Swing Event Model

Chapter 7: A First Look at GUI Applications

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

!"# $ %&# %####' #&() % # # # #&* # ## +, # -

Graphical User Interface (GUI)

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Name Section. CS 21a Introduction to Computing I 1 st Semester Final Exam

Chapter 12 Advanced GUIs and Graphics

FirstSwingFrame.java Page 1 of 1

AnimatedImage.java. Page 1

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

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

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Dr. Hikmat A. M. AbdelJaber

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

Laying Out Components. What is Widget Layout?

MIT AITI Swing Event Model Lecture 17

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

SINGLE EVENT HANDLING

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

CS 3331 Advanced Object-Oriented Programming Final Exam

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

Implementing Graphical User Interfaces

Transcription:

Steven Zeil October 25, 2013 Contents 1 Develop the Model 2 2 Develop the layout of those elements 3 3 Add listeners to the elements 9 4 Implement custom drawing 12 1

The StringArt Program To illustrate Java event handling, we ll look at a simple, but typical GUI interface to a graphic application StringArtjava Compiled version of this program The Process 1 Develop the model 2 Select the GUI elements to portray the model 3 Develop the layout of those elements 4 Add listeners to the elements 5 Implement custom drawing 1 Develop the Model Develop the Model The model is the underlying data that is being manipulated and portrayed by the program CS330 2

In this example, we need enough info to arrange the strings of various colors at appropriate steps around the circle / / The Model private Color [ ] colors ; private int stepsize = 5 ; The array will hold two colors Select the GUI elements to portray the model The core elements we will need: a canvas on which to draw the graphics * This is generally done with a JPanel A text entry box (JTextField) in which to enter the step size Two buttons (JButton) to activate the color choices How do we choose these? It helps to know what s available 2 Develop the layout of those elements Develop the layout of those elements There are two common approaches to laying out GUIs Manual arrangement using a program similar to a graphics editor (Visio, Dia, etc) but with GUI elements as the building blocks Easy & quick Resulting layouts are often inflexible * Respond badly to window s being resized * Or to being displayed on smaller screens, different operating systems, window managers, etc Programmed arrangement CS330 3

Takes more effort * Though not much more given the need to program behaviors of the elements Code can implement policies for resizing Programmed Approach in Java Uses a combination of Container/nesting relationships Layout managers GUI Container Elements Some GUI elements are containers that hold other elements The size and position of the container constrains the possible positions of the elements within it Internal positioning is controlled by a layout manager GUI Elements in StringArt The outermost container is a window (JFrame) This is a container Specifically, it contains a content pane We add elements to the content pane The window s content pane will contain Our drawing canvas (JPanel) and, beneath that, A control panel (JPanel) The control panel will contain The two buttons for choosing colors the test extry box for the step size CS330 4

Structural Summary JFrame Container content pane 1 1 Canvas JPanel control panel 1 stepsize 1 JTextField JButton color choosers 2 Where Did the Control Panel Come From? Java has a handful of rules for easily arranging elements horizontal rows vertical columns grids arranged around a center, etc It s easiest to break a desired arrangement down into a combination of these eg, horizontal row within the control panel, and vertical within the window CS330 5

Programming the Containment GUI container elements are handled much like utility containers public void createandshowgui() { window = new JFrame(); canvas = new JPanel () { ; canvassetbackground(colorwhite); windowgetcontentpane()add (canvas, BorderLayoutCENTER); canvassetpreferredsize(new Dimension(400, 400)); JPanel controls = new JPanel(); ❶ ❷ ❸ ❹ colorchooser1 = new JButton("Color 1"); controlsadd (colorchooser1); colorchooser2 = new JButton("Color 2"); controlsadd (colorchooser2); stepsizein = new JTextField (""+stepsize, 5); controlsadd (stepsizein); windowgetcontentpane()add (controls, BorderLayoutSOUTH); windowpack(); windowsetvisible(true); ❺ ❻ ❼ ❶ Create the window ❷ Create the canvas ❸ Add the canvas to the window s content pane ❹ Create the control panel ❺ Create the buttons and text field and add to the control panel ❻ Add the control panel to the window s content pane CS330 6

❼ Arrange the components of the GUI and display the window Laying out the components Java has several layout managers These give us several options for how to arrange our components Need to choose one for each container For the control panel, we want a horizontal row FlowLayout, BoxLayout, or BorderLayout would work FlowLayout is already the default for JPanels, so it s easiest to stick with that For the window s content pane, we want a vertical row BoxLayout or BorderLayout would work I chose BorderLayout Using Border Layout public void createandshowgui ( ) { window = new JFrame ( ) ; / / s e t up the components window getcontentpane ( ) setlayout ( new BorderLayout ( ) ) ; canvas = new JPanel ( ) { ; window getcontentpane ( ) add ( canvas, BorderLayout CENTER) ; JPanel controls = new JPanel ( ) ; window getcontentpane ( ) add ( controls, BorderLayout SOUTH) ; CS330 7

Miscellaneous Appearance Code public void createandshowgui() { window = new JFrame(); // set up the components windowgetcontentpane()setlayout (new BorderLayout()); canvas = new JPanel () { ; canvassetbackground(colorwhite); windowgetcontentpane()add (canvas, BorderLayoutCENTER); canvassetpreferredsize(new Dimension(400, 400)); ❶ JPanel controls = new JPanel(); colorchooser1 = new JButton("Color 1"); controlsadd (colorchooser1); setcolor(colorchooser1, colors[0]); colorchooser1addactionlistener (new ColorChooser(colorChooser1, 0)); colorchooser2 = new JButton("Color 2"); controlsadd (colorchooser2); setcolor(colorchooser2, colors[1]); colorchooser2addactionlistener (new ColorChooser(colorChooser2, 1)); stepsizein = new JTextField (""+stepsize, 5); controlsadd (stepsizein); stepsizeinaddactionlistener (new ActionListener() { public void actionperformed(actionevent e) { try { Integer newsize = new Integer(stepSizeIngetText()); stepsize = newsizeintvalue(); canvasrepaint(); catch (Exception ex) {; ); CS330 8

windowgetcontentpane()add (controls, BorderLayoutSOUTH); windowsetdefaultcloseoperation((startedinanapplet)? JFrameDISPOSE_ON_CLOSE : JFrameEXIT_O windowpack(); windowsetvisible(true); /** * Sets the background color of a button to the indicated color * Changes the foreground to wither black or white, depending on * which will give more contrast agasint the new background * * @param button * @param color */ private void setcolor(jbutton button, Color color) { buttonsetbackground(color); int brightness = colorgetred() + colorgetgreen() + colorgetblue(); // max of 3*255 if (brightness > 3*255/2) { else { // This is a fairly bright color Use black lettering buttonsetforeground (Colorblack); // This is a fairly dark color Use white lettering buttonsetforeground (Colorwhite); Most of the highlighted code is self-explanatory ❶ The canvas, a panel with no internal compoenents, has no natural size and tends to shrink to 0 0 if we aren t careful ❷ This utility function sets the background color of a button to match the color that it selects, and makes sure that the foreground color of the text is visible in contrast ❷ 3 Add listeners to the elements Add listeners to the elements CS330 9

We need to implement some behaviors Closing the window shuts down the program Entering a number in the text box changes the step size in the model Clicking a color button pops up a color selection dialog and updates the model Closing the Window Here we use a shorthand technqiue rather than create a full-fledged functor to listen: public void createandshowgui ( ) { window = new JFrame ( ) ; window setdefaultcloseoperation ( ( startedinanapplet )? JFrame DISPOSE_ON_CLOSE : JFrame EXIT_ON_CLOSE ) ; Entering the Step Size This is handled by an ActionListener, which is triggered when we hit Enter/Return with the cursor positioned in the text box stepsizein = new JTextField ( ""+stepsize, 5 ) ; controls add ( stepsizein ) ; stepsizein addactionlistener (new ActionListener ( ) { public void actionperformed ( ActionEvent e ) { try { Integer newsize = new Integer ( stepsizein gettext ( ) ) ; stepsize = newsize intvalue ( ) ; catch ( Exception ex ) { ; ) ; CS330 10

Color Selection Buttons notify an ActionListener when a button is clicked colorchooser1 = new JButton ( " Color 1" ) ; controls add ( colorchooser1 ) ; setcolor ( colorchooser1, colors [ 0 ] ) ; colorchooser1 addactionlistener ( new ColorChooser ( colorchooser1, 0 ) ) ; colorchooser2 = new JButton ( " Color 2" ) ; controls add ( colorchooser2 ) ; setcolor ( colorchooser2, colors [ 1 ] ) ; colorchooser2 addactionlistener ( new ColorChooser ( colorchooser2, 1 ) ) ; We implement this with our own subclass of ActionListener, ColorChooser ColorChooser private class ColorChooser implements ActionListener { private JButton button; ❶ private int colornum; public ColorChooser (JButton button, int colornum) { thisbutton = button; ❷ thiscolornum = colornum; ; @Override public void actionperformed(actionevent arg0) { ❸ Color chosen = JColorChoosershowDialog(window, "Choose a color", colors[colornum]); if (chosen!= null) { colors[colornum] = chosen; setcolor (button, chosen); canvasrepaint(); ❹ ❶ Each ColorChooser object will remember which button it is attached to and which of the two colors it controls CS330 11

❷ That info is gathered and remembered in the constructor ❸ Here is the function that we must provide if we are to implement ActionListener The JColorChooser invoked in the first line pops up the stnadard Java color selection box ❹ Once we have a selected color, we update the appropriate element of the model s colors array, and also change the button s coloring 4 Implement custom drawing Implement custom drawing The proper moment for drawing GUI elements is a bit tricky Think of some of the various situations in which all or part of a window needs to be redrawn: The program concludes some kind of computation and needs to display the results (ie, a program state change) We had previously clicked on the minimize/iconify control to reduce the window to an icon, and now we click on the icon to open it back up to a full window Implement custom drawing (cont) The window was completley or partially hidden beneath other windows and we Alt-tab to bring it back up to the top We drag another window or other item across the front of window, continuously hiding and revealing different potions of the window as we do so Any of these can force part or all of an application to need redrawing Some of these (state changes) are under direct program control Most are not paint and repaint Most GUI elements already take care of drawing themselves For elements with customized appearance: CS330 12

Programmer provides a paint function canvas = new JPanel ( ) { public void paint ( Graphics g ) { super paint ( g ) ; drawlines ( g, getsize ( ) ) ; ; Paint and Repaint We never call paint directly We call repaint() That asks the system to schedule a call to paint for sometime in the near future One reason for this indirect approach is that some actions (eg, dragging things on the screen) can result in lots of repaint requests being sent within a very short period of time If we actually had to redraw the GUI that often, machines with slower CPUs or graphics could be overwhelmed The run-time system is allowed to "buffer" multiple requests to repaint the same GUI elements, so long as it does eventually call paint() Repainting the StringArt Canvas private class ColorChooser implements ActionListener { private JButton button; private int colornum; public ColorChooser (JButton button, int colornum) { thisbutton = button; thiscolornum = colornum; @Override public void actionperformed(actionevent arg0) { Color chosen = JColorChoosershowDialog(window, "Choose a color", colors[colornum]); if (chosen!= null) { CS330 13

; colors[colornum] = chosen; setcolor (button, chosen); canvasrepaint(); public void createandshowgui() { window = new JFrame(); // set up the components windowgetcontentpane()setlayout (new BorderLayout()); canvas = new JPanel () { public void paint (Graphics g) { superpaint(g); drawlines (g, getsize()); ; canvassetbackground(colorwhite); windowgetcontentpane()add (canvas, BorderLayoutCENTER); canvassetpreferredsize(new Dimension(400, 400)); JPanel controls = new JPanel(); colorchooser1 = new JButton("Color 1"); controlsadd (colorchooser1); setcolor(colorchooser1, colors[0]); colorchooser1addactionlistener (new ColorChooser(colorChooser1, 0)); colorchooser2 = new JButton("Color 2"); controlsadd (colorchooser2); setcolor(colorchooser2, colors[1]); colorchooser2addactionlistener (new ColorChooser(colorChooser2, 1)); stepsizein = new JTextField (""+stepsize, 5); controlsadd (stepsizein); stepsizeinaddactionlistener (new ActionListener() { public void actionperformed(actionevent e) { CS330 14

); try { Integer newsize = new Integer(stepSizeIngetText()); stepsize = newsizeintvalue(); canvasrepaint(); catch (Exception ex) {; windowgetcontentpane()add (controls, BorderLayoutSOUTH); windowsetdefaultcloseoperation((startedinanapplet)? JFrameDISPOSE_ON_CLOSE : JFrameEXIT_O windowpack(); windowsetvisible(true); We request a repaint of the canvas after any operation that could change its appearance The Full Listing import javaawtborderlayout; import javaawtcolor; import javaawtdimension; import javaawtgraphics; import javaawteventactionevent; import javaawteventactionlistener; import javaawteventitemevent; import javaawteventitemlistener; import javaxswingjapplet; import javaxswingjbutton; import javaxswingjcolorchooser; import javaxswingjcombobox; import javaxswingjframe; import javaxswingjpanel; import javaxswingjtextfield; /** * A simple example of GUI event handling in a Java application CS330 15

* * This can be run as a main program or as an applet * * @author zeil * */ public class StringArt extends JApplet { private boolean startedinanapplet; // The Model private Color[] colors; private int stepsize = 5; // The View & Controls private JFrame window; private JPanel canvas; private JButton colorchooser1; private JButton colorchooser2; private JTextField stepsizein; private class ColorChooser implements ActionListener { private JButton button; private int colornum; public ColorChooser (JButton button, int colornum) { thisbutton = button; thiscolornum = colornum; @Override public void actionperformed(actionevent arg0) { Color chosen = JColorChoosershowDialog(window, "Choose a color", colors[colornum]); if (chosen!= null) { colors[colornum] = chosen; setcolor (button, chosen); canvasrepaint(); CS330 16

; public StringArt() { startedinanapplet = false; window = null; colors = new Color[2]; colors[0] = Colorred; colors[1] = Colorblue; public static void main (String[] args) { StringArt instance = new StringArt(); instancecreateandshowgui(); public void createandshowgui() { window = new JFrame(); // set up the components windowgetcontentpane()setlayout (new BorderLayout()); canvas = new JPanel () { public void paint (Graphics g) { superpaint(g); drawlines (g, getsize()); ; canvassetbackground(colorwhite); windowgetcontentpane()add (canvas, BorderLayoutCENTER); canvassetpreferredsize(new Dimension(400, 400)); JPanel controls = new JPanel(); colorchooser1 = new JButton("Color 1"); controlsadd (colorchooser1); setcolor(colorchooser1, colors[0]); CS330 17

colorchooser1addactionlistener (new ColorChooser(colorChooser1, 0)); colorchooser2 = new JButton("Color 2"); controlsadd (colorchooser2); setcolor(colorchooser2, colors[1]); colorchooser2addactionlistener (new ColorChooser(colorChooser2, 1)); stepsizein = new JTextField (""+stepsize, 5); controlsadd (stepsizein); stepsizeinaddactionlistener (new ActionListener() { public void actionperformed(actionevent e) { try { Integer newsize = new Integer(stepSizeIngetText()); stepsize = newsizeintvalue(); canvasrepaint(); catch (Exception ex) {; ); windowgetcontentpane()add (controls, BorderLayoutSOUTH); windowsetdefaultcloseoperation((startedinanapplet)? JFrameDISPOSE_ON_CLOSE : JFrameEXIT_O windowpack(); windowsetvisible(true); /** * Sets the background color of a button to the indicated color * Changes the foreground to wither black or white, depending on * which will give more contrast agasint the new background * * @param button * @param color */ private void setcolor(jbutton button, Color color) { buttonsetbackground(color); int brightness = colorgetred() + colorgetgreen() + colorgetblue(); // max of 3*255 if (brightness > 3*255/2) { CS330 18

// This is a fairly bright color Use black lettering buttonsetforeground (Colorblack); else { // This is a fairly dark color Use white lettering buttonsetforeground (Colorwhite); // Applet functions public void init() { startedinanapplet = true; public void start() { if (window == null) createandshowgui(); public void stop() { public void destroy() { int interpolate (int x, int y, int i, int steps) { return (i * x + (steps-i)*y) / steps; Color interpolate(color c1, Color c2, int i, int steps) { return new Color (interpolate(c1getred(), c2getred(), i, steps), interpolate(c1getgreen(), c2getgreen(), i, steps), interpolate(c1getblue(), c2getblue(), i, steps)); CS330 19

class Point { double x; double y; Point ptoncircle (int degrees, int radius, Point center) { Point p = new Point(); double theta = MathtoRadians((double)degrees); px = centerx + (double)radius * Mathcos(theta); py = centery + (double)radius * Mathsin(theta); return p; public void drawlines(graphics g, Dimension d) { int dmin = (dwidth < dheight)? dwidth : dheight; if (stepsize < 1) stepsize = 1; Point center = new Point(); centerx = (double)dwidth/20; centery = (double)dheight/20; for (int i = 0; i < 60; ++i) { Point origin = ptoncircle(6*i, dmin/2, center); int j = i + stepsize; while (j >= 60) j -= 60; while (i!= j) { Point destination = ptoncircle(6*j, dmin/2, center); gsetcolor(interpolate(interpolate(colors[0], colors[1], i%30, 30), interpolate(colors[0], colors[1], j, 60), 1, 2)); gdrawline ((int)originx, (int)originy, (int)destinationx, (int)destinationy); j += stepsize; CS330 20

while (j >= 60) j -= 60; CS330 21