EE2E1. JAVA Programming Lecture 5 Graphics programming and Swing.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
©2004 Brooks/Cole Applets Graphics & GUIs. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Graphical Programs Most applications these days are.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
2D Graphics in Java COMP53 Nov 14, Applets and Applications Java applications are stand-alone programs – start execution with main() – runs in JVM.
Advanced Java Class GUI – part 1. Intro to GUI GUI = Graphical User Interface -- “Gooey” Just because it’s “gooey” does not mean you may write messy code.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Swing Graphics ● Empty Swing containers have no visual appearance except for a background color ● Every JComponent must have a paintComponent method that.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Web Design & Development Lecture 18. Java Graphics.
GUI Basics: Introduction. Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your.
Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
Introducing Graphics There are generally two types of graphics facilities in Java –Drawing –GUIs We concentrate on drawing here We will draw on a Graphics.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
JAPPLET.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
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.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 Object-Oriented Languages.
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.
Chapter 7 Graphics. © Daly and Wrigley Objectives Use Graphic Components: ▫ Strings ▫ Lines ▫ Rectangles ▫ Ovals ▫ Arcs Change the color and font of elements.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
Objectives of This Session
Graphics Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
1 Java Swing - Lecture 2 Components and Containment Boriana Koleva
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
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.
Creating Windows. How can we use Java to create programs that use windows (GUI applications)? How can we use Java to create programs that use windows.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Swing Components. Introduction Swing – A set of GUI classes – Part of the Java's standard library –Much better than the previous library: AWT Abstract.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Basics of GUI Programming Chapter 11 and Chapter 22.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
Java Swing One of the most important features of Java is its ability to draw graphics.
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
EE2E1. JAVA Programming Lecture 5 Graphics programming and Swing.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
C Sc 335 Object-Oriented Programming and Design Rick Mercer
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
Graphics JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
A Quick Java Swing Tutorial
Chapter 8 Graphics.
Basic Graphics Chapter 5 3/19/15 Thursday Section Only
A Quick Java Swing Tutorial
Chapter 10 Graphics.
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
A Quick Java Swing Tutorial
Chapter 8 Graphics.
Presentation transcript:

EE2E1. JAVA Programming Lecture 5 Graphics programming and Swing

Contents Overview of graphics in Java – AWT & Swing Overview of graphics in Java – AWT & Swing Frames Frames Swing inheritance hierarchy Swing inheritance hierarchy Displaying graphics in frames – panels Displaying graphics in frames – panels Displaying text in graphics windows Displaying text in graphics windows Drawing simple graphics Drawing simple graphics Digital image processing in Java Digital image processing in Java

Overview of graphics in Java – AWT & Swing Most modern application programs use sophisticated graphics and have powerful graphical user interfaces Most modern application programs use sophisticated graphics and have powerful graphical user interfaces  Spreadsheets  Word processing  Web browsers  programs Its important to extend our knowledge from writing crude console-based programs to portable graphical applications Its important to extend our knowledge from writing crude console-based programs to portable graphical applications

Java, unlike C & C++, has standard packages for graphics Java, unlike C & C++, has standard packages for graphics 2 related packages and sub-packages support graphics in Java 2 related packages and sub-packages support graphics in Java  java.awt (Abstract Windows Toolkit)  javax.swing AWT is ‘peer-based’ AWT is ‘peer-based’  Depends on graphical elements native local platform’s graphics system  Unix/Windows graphical programs written using AWT will have a different ‘look and feel’

Swing is much more platform independent Swing is much more platform independent  Graphical components are pre-built and are simply painted onto windows  Relies less on the underlying runtime environment  Usually slower than AWT-based programs In practice graphical programs are a mixture of Swing and AWT classes In practice graphical programs are a mixture of Swing and AWT classes  AWT takes care of all of the event handling for GUI’s (see later)

Frames A frame is a top level window which is a container for graphical components (canvas, buttons, menus etc) A frame is a top level window which is a container for graphical components (canvas, buttons, menus etc) The AWT has a Frame class and Swing has a JFrame class The AWT has a Frame class and Swing has a JFrame class The following program displays an empty frame The following program displays an empty frame

import javax.swing.*; class MyFrame extends JFrame { public MyFrame() { setTitle("My first graphics program"); setSize(400,300); } public class FrameTest { public static void main(String[] args) { JFrame frame=new MyFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

A class MyFrame is defined which is a sub-class of JFrame A class MyFrame is defined which is a sub-class of JFrame  A title is added  The frame is sized to 400x300 (by default, a frame is 0x0) The frame is created by a call to the constructor The frame is created by a call to the constructor The application terminates when the window is closed The application terminates when the window is closed The frame is displayed by a call to JFrame.setVisible(true) The frame is displayed by a call to JFrame.setVisible(true)  This creates a separate thread which runs until the program is terminated – the main thread terminates

Swing inheritance hierarchy The JFrame class inherits attributes from higher level container classes The JFrame class inherits attributes from higher level container classes  Typically for resizing and positioning frames Class names beginning with ‘J’ are Swing classes – everything else is part of AWT Class names beginning with ‘J’ are Swing classes – everything else is part of AWT

ComponentFrameWindowContainer JFrame JComponent JPanel …..

Most swing components (for example JPanel) are derived from the JComponent class Most swing components (for example JPanel) are derived from the JComponent class JFrame, being a top level window, is derived from the Window class JFrame, being a top level window, is derived from the Window class Other top level windows include JApplet and JDialog Other top level windows include JApplet and JDialog

Top Level Containers : JDialog javax.swing.JDialog : javax.swing.JDialog :  More simple and limited than frames  Typically used for showing a short message on the screen  Also has a border and a title bar  Use the static method of JoptionPane to show standard dialog boxes: JOptionPane.showMessageDialog(null, "4+2=6");

14 Top Level Containers:JFileChooser javax.swing.JFileChooser : javax.swing.JFileChooser :  Allows the the user to choose a file  Supports “open” and “save”: showOpenDialog(),showSaveDialog()‏ JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());

Top Level Containers: JFrame javax.swing.JFrame : javax.swing.JFrame :  Top-level window with a title and a border.  Usually used as a program's main window

16 Internal Containers Not Top level containers Not Top level containers Can contain other non-top level components Can contain other non-top level components Examples: Examples: – JScrollPane : Provides a scrollable view of its components – JSplitPane : Separates two components – JTabbedPane : User chooses which component to see

Displaying graphics in frames – panels Frames are containers – they can contain other user interface/graphical components Frames are containers – they can contain other user interface/graphical components A frame contains a content pane into which components can be added A frame contains a content pane into which components can be added The following code is typical The following code is typical Container contentPane=frame.getContentPane(); Component c= ….; // UI or graphical component contentPane.add (c);// Add to the frame

Content pane Frame

Panels Panels (JPanel class) are added to the content pane Panels (JPanel class) are added to the content pane Panels are themselves containers Panels are themselves containers  The can contain other UI components  They also have a surface onto which graphics can be drawn  Text  Basic shapes (lines, boxes etc)  Images

CIS 068 Panels Panels themselves are general purpose containers allowing other graphics components to be easily added Panels themselves are general purpose containers allowing other graphics components to be easily added JPanel JFrame

Drawing on panels The paintComponent() method in JComponent (a superclass of JPanel) must be overridden The paintComponent() method in JComponent (a superclass of JPanel) must be overridden paintComponent() is called automatically when the window has to be drawn or redrawn – for example when it is moved by the user. It is also called when the repaint() method of a panel is called paintComponent() is called automatically when the window has to be drawn or redrawn – for example when it is moved by the user. It is also called when the repaint() method of a panel is called

The following code creates a class MyPanel into which graphics can be drawn The following code creates a class MyPanel into which graphics can be drawn class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); // Code placed here to draw graphics }

The Graphics object defines the graphics context (fonts, line styles, colours etc) The Graphics object defines the graphics context (fonts, line styles, colours etc) A call to super.paintComponent() calls the paintComponent() method in JComponent (the base class of JPanel) A call to super.paintComponent() calls the paintComponent() method in JComponent (the base class of JPanel)  This call sets up the graphics context and performs other complex tasks

Displaying text in graphics windows Text can be drawn onto panels using the Graphics.drawString() method Text can be drawn onto panels using the Graphics.drawString() method The text font and size can be optionally set/reset The text font and size can be optionally set/reset The following program draws a string onto a panel The following program draws a string onto a panel  The panel is then added to a frame which is then displayed using JFrame.setVisible(true)

import javax.swing.*; import java.awt.*; public class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Hello there!",150,125); }

import java.awt.event.*; import javax.swing.*; import java.awt.*; public class HelloFrame extends JFrame { public HelloFrame() { setTitle("Drawing a string example"); setSize(400,300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane=getContentPane(); contentPane.add(new MyPanel()); }

public class FrameTest { public static void main(String[] args) { JFrame frame=new HelloFrame(); frame.setVisible(true); }

Text fonts can be set/reset Text fonts can be set/reset  The existing font applies until it is reset The following code sets a bold Helvetica font with a larger font size The following code sets a bold Helvetica font with a larger font size public class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Font f=new Font(“Helvetica”,Font.BOLD,25); g.setFont(f); g.drawString("Hello there!",150,125); }

Drawing simple graphics Class java.awt.Graphics contains methods which allow simple graphics to be drawn in different colours Class java.awt.Graphics contains methods which allow simple graphics to be drawn in different colours Graphics.setcolor() sets the drawing colour Graphics.setcolor() sets the drawing colour  Colour is represented by the class java.awt.Color(int red, int blue, int green) defining the RGB components  Preset constants exist (defined as static constants in Color)  Color.red  Color.orange  Color.pink  etc

Examples of different shapes Examples of different shapes  Graphics.drawLine(int x1, int y1, int x2, int y2) draws a straight line from (x1,y1) to (x2,y2)  Graphics.drawRect(int x, int y, int w, int h) draws a rectangle from upper left hand corner (x,y) with width w and height h  Graphics.drawOval(int x, int y, int w, int h) draws an outline of an ellipse with a ‘bounding rectangle’ as above  Graphics.drawPolygon(int[] xc, int[] yc, int n) draws a polygon with n vertices with the co- ordinates being stored in arrays xc and yc  Graphics.fillOval (int x, int y, int w, int h) fills the oval with the current draw colour

class DrawPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.drawRect(20,30,50,50); g.setColor(Color.green); g.drawOval(100,30,90,60); g.fillOval(100,30,90,60); g.setColor(Color.yellow); int[] xcoords={180,200,250,275,225}; int[] ycoords={170,130,130,150,200}; g.drawPolygon(xcoords,ycoords,5); g.fillPolygon(xcoords,ycoords,5); }

35 Swing Components

Swing components We will see in the next lecture how we can put these together to build graphical user interfaces (GUI’s) We will see in the next lecture how we can put these together to build graphical user interfaces (GUI’s) Swing tutorial Swing tutorial Swing tutorial Swing tutorial Swing component examples Swing component examples Swing component examples Swing component examples

Digital Image Processing in Java Digital Image Processing (DIP) deals with manipulation of digital images using a digital computer   Java can support and handle digital image processing efficiently using various functions.

Digital Image Processing in Java Java BufferedImage class is a subclass of the Image class Java BufferedImage class is a subclass of the Image class  It is used to handle and manipulate the image data  All BufferedImage objects have an upper left corner coordinate of (0, 0)  Documented in /BufferedImage.html /BufferedImage.html /BufferedImage.html x y pixel

Digital Image Processing in Java Creating a BufferedImage object is easy  Both RGB and Greyscale images can be created  BufferedImage.TYPE_INT_RGB specifies RGB  BufferedImage.TYPE_INT_ARGB specified RGB with an additional alpha (transparency channel)  BufferedImage.TYPE_BYTE_GRAY specifies greyscale  etc import java.awt.image.BufferedImage;... BufferedImage img = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB);

Digital Image Processing in Java Using a BufferedImage object to read/write pixels is easy int r = 10; // red component int g = 20; // green component int b = 30; // blue component int col = (r << 16) | (g << 8) | b; img.setRGB(x, y, col); Colour c = new Color(img.getRGB(x, y)); int red=c.getRed(); int green=c.getGreen(); int blue=c.getBlue();

Digital Image Processing in Java Reading and writing a BufferedImage object from/to file is also easy   A variety of file types (jpg, png etc) can be used   png is losless, jpg is lossy   Other file types can be created such as gif, bmp etc.   Makes use of the utility class javax.imageio.ImageIO and static methods read(…) and write(…)   Check the docs for details!

Digital Image Processing in Java Example code snippet import javax.imageio.ImageIO; import java.io.File; import java.awt.image.BufferedImage; public class ImageIOExample { public static void main(String[] args) { BufferedImage bImage = null; try{ File image = new File(“myImageFile"); bImage = ImageIO.read(image); ImageIO.write(bImage, “png", new File("/image.png"));/image.png ImageIO.write(bImage, “gif", new File("myDir/image.gif"));myDir/image. } catch(Exception e){} }

Digital Image Processing in Java Displaying a BufferedImage object is also easy   We use the drawImage() method in a the JPanel class public class ImagePanel extends Jpanel { private BufferedImage image; public ImagePanel() {….} protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, null); }

Digital Image Processing in Java import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import javax.swing.*; import java.awt.*; public class ImageIOExample { public static void main(String[] args) { BufferedImage bImage = null; try{ File image = new File("Rooney.jpg"); bImage = ImageIO.read(image); } catch(Exception e){} JFrame frame=new JFrame(); frame.setSize(400,500); ImagePanel panel=new ImagePanel(bImage); Container contentPane=frame.getContentPane(); contentPane.add(panel); frame.setVisible(true); }

Digital Image Processing in Java class ImagePanel extends JPanel { private BufferedImage image; public ImagePanel(BufferedImage im) {image=im;} protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, null); } class ImageProcessor { // Add our image processing algorithms here! }

Digital Image Processing in Java class ImageProcessor { // Add our image processing algorithms here! private BufferedImage image; public ImageProcessor(BufferedImage im) {image=im;} public void toGreyscale() { for (int x=0; x<image.getWidth(); x++) for (int y=0; y<image.getHeight(); y++) { Color c = new Color(image.getRGB(x, y)); int red=c.getRed(); int green=c.getGreen(); int blue=c.getBlue(); int grey=(red+green+blue)/3; // roughly! Color greyRGB=new Color(grey,grey,grey); image.setRGB(x,y,greyRGB.getRGB()); }

Digital Image Processing in Java As an exercise, see if you can create an ImageProcessor object within the ImageIOExample main method and then call it’s toGreyscale() method As an exercise, see if you can create an ImageProcessor object within the ImageIOExample main method and then call it’s toGreyscale() method

And finally …. Swing/AWT are massive and complex Swing/AWT are massive and complex  We have only scratched the surface Typically Java API’s have been built on top of Swing Typically Java API’s have been built on top of Swing  Java2D  Java3D In practice, you would use these to do real work for example involving image processing or 3D rendering In practice, you would use these to do real work for example involving image processing or 3D rendering