ee2e1. java programming lecture 5 graphics programming and swing
Post on 19-Dec-2015
228 Views
Preview:
TRANSCRIPT
EE2E1. JAVA Programming
Lecture 5Lecture 5
Graphics programming and SwingGraphics programming and Swing
Contents Overview of graphics in Java – AWT & SwingOverview of graphics in Java – AWT & Swing FramesFrames Swing inheritance hierarchySwing inheritance hierarchy Displaying graphics in frames – panelsDisplaying graphics in frames – panels Displaying text in graphics windowsDisplaying text in graphics windows Drawing simple graphicsDrawing simple graphics Digital image processing in JavaDigital image processing in Java
Overview of graphics in Java – AWT & Swing
Most modern application programs use sophisticated Most modern application programs use sophisticated graphics and have powerful graphical user interfacesgraphics and have powerful graphical user interfaces SpreadsheetsSpreadsheets Word processingWord processing Web browsersWeb browsers Email programsEmail programs
Its important to extend our knowledge from writing Its important to extend our knowledge from writing crude console-based programs to portable graphical crude console-based programs to portable graphical applicationsapplications
Java, unlike C & C++, has standard packages for graphicsJava, unlike C & C++, has standard packages for graphics
2 related packages and sub-packages support graphics in Java2 related packages and sub-packages support graphics in Java
java.awt (java.awt (AAbstract bstract WWindows indows TToolkit)oolkit)
javax.swingjavax.swing
AWT is ‘peer-based’AWT is ‘peer-based’
Depends on graphical elements native local platform’s Depends on graphical elements native local platform’s graphics systemgraphics system
Unix/Windows graphical programs written using AWT Unix/Windows graphical programs written using AWT will have a different ‘look and feel’ will have a different ‘look and feel’
Swing is much more platform independent Swing is much more platform independent
Graphical components are Graphical components are pre-builtpre-built and are and are simply painted onto windowssimply painted onto windows
Relies less on the underlying runtime Relies less on the underlying runtime environmentenvironment
Usually slower than AWT-based programsUsually slower than AWT-based programs
In practice graphical programs are a mixture of In practice graphical programs are a mixture of Swing and AWT classes Swing and AWT classes
AWT takes care of all of the event handling for AWT takes care of all of the event handling for GUI’s (see later)GUI’s (see later)
Frames
A A frame frame is a top level window which is a is a top level window which is a containercontainer for graphical components for graphical components (canvas, buttons, menus etc)(canvas, buttons, menus etc)
The AWT has a The AWT has a FrameFrame class and Swing has class and Swing has a a JFrame JFrame classclass
The following program displays an empty The following program displays an empty frameframe
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 A class MyFrameMyFrame is defined which is a sub-class of is defined which is a sub-class of JFrameJFrame A title is addedA title is added The frame is sized to 400x300 (by default, a frame The frame is sized to 400x300 (by default, a frame
is 0x0)is 0x0) The frame is created by a call to the constructorThe frame is created by a call to the constructor The application terminates when the window is The application terminates when the window is
closedclosed The frame is displayed by a call to The frame is displayed by a call to
JFrame.setVisible(true)JFrame.setVisible(true) This creates a separate thread which runs until the This creates a separate thread which runs until the
program is terminated – the program is terminated – the mainmain thread terminates thread terminates
Swing inheritance hierarchy
The JFrame class inherits attributes from The JFrame class inherits attributes from higher level container classeshigher level container classes Typically for resizing and positioning Typically for resizing and positioning
framesframes Class names beginning with ‘J’ are Swing Class names beginning with ‘J’ are Swing
classes – everything else is part of AWTclasses – everything else is part of AWT
Component
Frame
Window
Container
JFrame
JComponent
JPanel…..
Most swing components (for example Most swing components (for example JPanel) JPanel) are derived from the are derived from the JComponent JComponent classclass
JFrame, JFrame, being a top level window, is being a top level window, is derived from the derived from the Window Window classclass
Other top level windows include Other top level windows include JAppletJApplet and and JDialogJDialog
Top Level Containers : JDialog javax.swing.JDialogjavax.swing.JDialog::
More simple and limited than framesMore simple and limited than frames Typically used for showing a short message on the screenTypically used for showing a short message on the screen Also has a border and a title barAlso has a border and a title bar Use the static method of JoptionPane to show standard Use the static method of JoptionPane to show standard
dialog boxes:dialog boxes:JOptionPane.showMessageDialog(null, "4+2=6");JOptionPane.showMessageDialog(null, "4+2=6");
14
Top Level Containers:JFileChooser
javax.swing.JFileChooserjavax.swing.JFileChooser:: Allows the the user to choose a fileAllows the the user to choose a file Supports “open” and “save”: Supports “open” and “save”: showOpenDialog(),showSaveDialog()showOpenDialog(),showSaveDialog()
JFileChooser fc = new JFileChooser();JFileChooser fc = new JFileChooser();int returnVal = fc.showOpenDialog(null);int returnVal = fc.showOpenDialog(null);if(returnVal == JFileChooser.APPROVE_OPTION)if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile()); System.out.println("File: " + fc.getSelectedFile());
Top Level Containers: JFrame javax.swing.JFramejavax.swing.JFrame::
Top-level window with a title and a border.Top-level window with a title and a border. Usually used as a program's main windowUsually used as a program's main window
16
Internal Containers
Not Top level containersNot Top level containers Can contain other non-top level componentsCan contain other non-top level components Examples:Examples:
– JScrollPaneJScrollPane: Provides a scrollable view of its : Provides a scrollable view of its componentscomponents
– JSplitPaneJSplitPane: Separates two components : Separates two components
– JTabbedPaneJTabbedPane: User chooses which: User chooses whichcomponent to seecomponent to see
Displaying graphics in frames – panels Frames are containers – they can contain Frames are containers – they can contain
other user interface/graphical componentsother user interface/graphical components A frame contains a A frame contains a content panecontent pane into which into which
components can be addedcomponents can be added The following code is typicalThe 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 (Panels (JPanelJPanel class) are added to the content class) are added to the content
panepane Panels are themselves containersPanels are themselves containers
The can contain other UI componentsThe can contain other UI components They also have a surface onto which graphics They also have a surface onto which graphics
can be drawncan be drawnTextTextBasic shapes (lines, boxes etc)Basic shapes (lines, boxes etc)ImagesImages
CIS 068
Panels
Panels themselves are general purpose containers Panels themselves are general purpose containers allowing other graphics components to be easily allowing other graphics components to be easily addedadded
JPanel
JFrame
Drawing on panels
The The paintComponent()paintComponent() method in method in JComponent JComponent (a superclass of(a superclass of JPanel JPanel) must ) must be overriddenbe overridden
paintComponent()paintComponent() is called automatically is called automatically when the window has to be drawn or when the window has to be drawn or redrawn – for example when it is moved by redrawn – for example when it is moved by the user. It is also called when the the user. It is also called when the repaint()repaint() method of a panel is calledmethod of a panel is called
The following code creates a class The following code creates a class MyPanel MyPanel into which graphics can be drawninto which graphics can be drawn
class MyPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
// Code placed here to draw graphics}
}
The The GraphicsGraphics object defines the graphics object defines the graphics context (fonts, line styles, colours etc)context (fonts, line styles, colours etc)
A call to A call to super.paintComponent()super.paintComponent() calls the calls the paintComponent()paintComponent() method in method in JComponentJComponent (the base class of (the base class of JPanelJPanel))
This call sets up the graphics context and This call sets up the graphics context and performs other complex tasksperforms other complex tasks
Displaying text in graphics windows Text can be drawn onto panels using the Text can be drawn onto panels using the
Graphics.drawString()Graphics.drawString() method method
The text font and size can be optionally set/resetThe text font and size can be optionally set/reset
The following program draws a string onto a panelThe following program draws a string onto a panel
The panel is then added to a frame which is The panel is then added to a frame which is then displayed using then displayed using JFrame.setVisible(true)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/resetText fonts can be set/reset The existing font applies until it is resetThe existing font applies until it is reset
The following code sets a bold Helvetica The following code sets a bold Helvetica font with a larger font sizefont 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 Class java.awt.Graphicsjava.awt.Graphics contains methods which contains methods which
allow simple graphics to be drawn in different coloursallow simple graphics to be drawn in different colours Graphics.setcolor() Graphics.setcolor() setssets the drawing colourthe drawing colour
Colour is represented by the class Colour is represented by the class java.awt.Color(int red, int blue, int green) java.awt.Color(int red, int blue, int green) defining defining the RGB componentsthe RGB components
Preset constants exist (defined as static constants in Preset constants exist (defined as static constants in Color)Color)
Color.redColor.redColor.orangeColor.orangeColor.pinkColor.pinketcetc
Examples of different shapesExamples of different shapes Graphics.drawLine(int x1, int y1, int x2, int y2)Graphics.drawLine(int x1, int y1, int x2, int y2) draws a draws a
straight line from straight line from (x1,y1)(x1,y1) to to (x2,y2)(x2,y2) Graphics.drawRect(int x, int y, int w, int h)Graphics.drawRect(int x, int y, int w, int h) draws a draws a
rectangle from upper left hand corner rectangle from upper left hand corner (x,y)(x,y) with width with width w w and height and height hh
Graphics.drawOval(int x, int y, int w, int h)Graphics.drawOval(int x, int y, int w, int h) draws an draws an outline of an ellipse with a ‘bounding rectangle’ as aboveoutline of an ellipse with a ‘bounding rectangle’ as above
Graphics.drawPolygon(int[] xc, int[] yc, int n)Graphics.drawPolygon(int[] xc, int[] yc, int n) draws a draws a polygon with polygon with nn vertices with the co-ordinates being vertices with the co-ordinates being stored in arrays stored in arrays xc xc and and ycyc
Graphics.fillOval (int x, int y, int w, int h)Graphics.fillOval (int x, int y, int w, int h) fills the oval fills the oval with the current draw colourwith 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
Swing components We will see in the next lecture how we can We will see in the next lecture how we can
put these together to build graphical user put these together to build graphical user interfaces (GUI’s)interfaces (GUI’s)
Swing tutorialSwing tutorial Swing component examplesSwing 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 Java BufferedImageBufferedImage class is a subclass of the class is a subclass of the ImageImage class class
It is used to handle and manipulate the image data It is used to handle and manipulate the image data All All BufferedImageBufferedImage objects have an upper left corner coordinate of (0, objects have an upper left corner coordinate of (0,
0)0)
Documented in Documented in http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImhttp://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html age.html
xy
pixel
Digital Image Processing in Java Creating a BufferedImage object is easy
Both RGB and Greyscale images can be createdBoth RGB and Greyscale images can be created
BufferedImage.TYPE_INT_RGB specifies RGBBufferedImage.TYPE_INT_RGB specifies RGB BufferedImage.TYPE_INT_ARGB specified RGB with an BufferedImage.TYPE_INT_ARGB specified RGB with an
additional alpha (transparency channel)additional alpha (transparency channel) BufferedImage.TYPE_BYTE_GRAY specifies greyscaleBufferedImage.TYPE_BYTE_GRAY specifies greyscale etcetc
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 easyint r = 10; // red component 0...255 int g = 20; // green component 0...255 int b = 30; // blue component 0...255 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 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"));ImageIO.write(bImage, “gif",
new File("myDir/image.gif"));}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 Javaimport 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 Javaclass 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 As an exercise, see if you can create an ImageProcessorImageProcessor object within the object within the ImageIOExample ImageIOExample main method and then main method and then call it’s call it’s toGreyscale() toGreyscale() methodmethod
And finally …. Swing/AWT are massive and complexSwing/AWT are massive and complex
We have only scratched the surfaceWe have only scratched the surface Typically Java API’s have been built on top of Typically Java API’s have been built on top of
SwingSwing Java2DJava2D Java3DJava3D
In practice, you would use these to do In practice, you would use these to do realreal work work for example involving image processing or 3D for example involving image processing or 3D renderingrendering
top related