====== Java: User Interface Components and 2D Graphics ====== ---- ===== User Interface and Interactive Components ===== * A good GUI API or package would allow you to ... * Create user interface components * Customize the behavior of the components * group and arrange the controls on the screen * access window manager facilities (e.g., reading image files, printing, and identifying which window is focused) * User interface (WIMP - "Window, Icon, Menu, Pointing device"): * Window * Buttons * Menus * Text boxes * Dialog boxes * Event handling: * Mouse * Keyboard * Focus / window * These are the essentials of writing graphics-based applications ===== The Java Approach ===== * Abstract Window Toolkit (AWT) - Native "peer" code; operating system dependent * Not all platforms support the same widget set (some are richer than others) * Also, different bugs in the AWT user interface library exist on different platforms * Widgets may have different behaviors on different platforms * Swing - Consistent user experience across platforms; less dependent on underlying platform, as compared to AWT * Many Swing components (classes) extend AWT components (classes). * Thus, both the AWT and Swing libraries are necessary (in most cases). * Container - A user interface component that can contain other user interface components such as buttons and text fields * Events * Toolkit - Class that gets system-dependent information (e.g., getting the screen size) ==== The JFrame Container ==== * The top level window (that is, a window that is not contained inside another window) * JFrame class of the Swing library * JFrame extends the Frame class of the AWT library * JFrame is a container * Pertinent methods: * setSize() * setLocation() * setTitle() * setIconImage() * setVisible() ==== The JPanel Container ==== * JPanel class of the Swing library * Provides the internal structure of a JFrame * Is itself a container * Has a surface onto which you can draw via paint() or paintComponent() methods * Some Java game developers use Canvas (AWT) instead of JPanel (Swing) * The difference: a JPanel can contain other components while a Canvas cannot * paint() is used for Canvas. * paint() can also be used in JPanel. ==== Swing User Interface Components ==== * JButton * JTextField * JLabel * JCheckBox * JRadioButton * JComboBox * JMenuBar * JPasswordField ==== Event Handling ==== * Event source (the widgets): button, text box, radio button, etc. * In response to mouse movement/click, keyboard press, etc. * Event listener - An object to which a component has delegated the task of handling a particular kind of event * The event source sends out event objects to all registered listeners when that event occurs. * The listener objects will then use the information in the event object to determine their reaction to the event. === Handling Mouse Clicking Events === * MouseListener interface * Uses MouseEvent class * Required methods: * public void mouseClicked(MouseEvent e) * public void mousePressed(MouseEvent e) * public void mouseReleased(MouseEvent e) * public void mouseEntered(MouseEvent e) * public void mouseExited(MouseEvent e) === Handling Keyboard Events === * Require FocusListener, KeyListener interfaces * Uses KeyEvent class * Required methods: * public void keyPressed (KeyEvent e) * public void keyTyped (KeyEvent e) * public void keyReleased (KeyEvent e) * public void focusGained (FocusEvent e) * public void focusLost (FocusEvent e) ----- ===== 2D Graphics ===== ==== Vector vs. Raster Graphics ==== * Vector: * Drawings defined as lines; no curves and limited colors * Benefits: No jagged lines (aliasing); only store endpoints of lines * Examples: Asteroids, Lunar Lander and Battlezone {{http://retrothing.typepad.com/photos/uncategorized/vector.jpg?180}} {{http://2.bp.blogspot.com/_gumEstDHdWE/TKAfNC3FdYI/AAAAAAAAAtI/5z8olS5b9Dc/s1600/Ataris-1983-Star-Wars-arcade-game-featured-simple-vector-graphics-but-at-the-time-the-experience-was-mind-blowing,O-Z-94211-13.jpg?180}} {{http://images.148apps.com/2012/5/38693/122582/luxorevolved1-300x225.png?180}} * Raster: * Screen is made up of pixels * Colors are defined by mixtures of 3 color sources: red, green, and blue (RGB) * Benefits: Can easily draw solid surfaces; cheaper * Drawbacks: More memory-intensive (but memory is cheap); aliasing problems {{http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Cadin%20Batrack/2012/12/28/retroGames_Raster.jpg}} ==== 2D Rendering Primitives ==== * Point * Line * Polygon * Closed (all lines connected) * Defined by a list of vertices ==== Coordinate System ==== * Two coordinate spaces in Java * User space - Where the graphics primitives are defined; device independent * Device space - The coordinate system of an output device, such as a screen, window, or a printer; device dependent * The necessary conversions between user space and device space are performed automatically during rendering ---- ===== 2D Graphics in Java ===== * Links: * http://java.sun.com/docs/books/tutorial/2d/index.html * http://courses.coreservlets.com/Course-Materials/java5.html (follow "Desktop Graphics in Java" link) * Uses older Graphics class but still useful: * http://www.csse.monash.edu.au/~cema/courses/CSE5910/lectureFiles/lecture7b.htm * The Graphics class * Introduced in JDK version 1.0 * Methods to draw lines and basic shapes * Very limited drawing options (e.g., cannot vary the line thickness; cannot rotate shapes) * The Graphics2D class * Allows newer type of Graphics object: Graphics2D extends Graphics * More sophisticated control over geometry, coordinate transformations, color management, and text layout * Supports shape manipulations * Packages (Java 2D API) * java.awt.* * The main package for the Java Abstract Window Toolkit. * java.awt.geom.* * The Java standard library of two dimensional geometric shapes such as lines, ellipses, and quadrilaterals. * java.awt.font.* * The library for manipulating glyphs in Java. * java.awt.color.* * The library dealing with the many different ways that color can be represented. * java.awt.image.* * The library for manipulating graphical images. ==== The Java 2D paintComponent() Method in a JPanel ==== public void paintComponent (Graphics g) { Graphics2D g2 = (Graphics2D)g; // This is where you will do your work ... ... } ==== Old Graphics Primitive Methods (That Still Work) ==== * drawLine(int x1, int y1, int x2, int y2) * drawRect(int x, int y, int width, int height) * fillRect(int x, int y, int width, int height) * drawOval(int x, int y, int width, int height) * fillOval(int x, int y, int width, int height) * drawString(String str, int x, int y) * drawPolygon(int[] xPoints, int[] yPoints, int nPoints) * fillPolygon(int[] xPoints, int[] yPoints, int nPoints) * For more, see http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html ==== Colors ==== * Use setColor() or setPaint() * A number of standard colors in Java: * Color.white * Color.red * Color.blue * Color.cyan * Color.green * Or, specify your own color using RGB values * Color(int r, int g, int b) * Color(float r, float g, float b) {{ http://www.csse.monash.edu.au/~cema/courses/CSE5910/lectureFiles/images/lect8a/lect8aGraphicsClassHierarchy.png?250|Class Diagram for (some of) Java's graphics routines}} ==== Graphics2D Primitive Methods ==== * Geometric shapes are organized in an object-oriented fashion * Line2D * Rectangle2D * Ellipse2D * The three classes above implement the Shape interface * To draw a shape, create an object of a class that implements the Shape interface and then call the draw() or fill() method of the Graphics2D class. * setStroke() - Set the line width. * Need to create a stroke via BasicStroke() * Rectangle2D.Double(double x, double y, double w, double h) * Rectangle2D.Float(float x, float y, float w, float h) * Ellipse2D.Double(double x, double y, double w, double h) * Ellipse2D.Float(float x, float y, float w, float h) * Point2D.Double(double x, double y) * Line2D.Double(Point2D start, Point2D end) * Line2D.Double(double startX, double startY, double endX, double endY) * Arc2D.Double(double x, double y, double w, double h, double start, double extent, int type) * Arc2D.Float(float x, float y, float w, float h, float start, float extent, int type) * RoundRectangle2D.Double(double x, double y, double w, double h, double arcw, double arch) * RoundRectangle2D.Float(float x, float y, float w, float h, float arcw, float arch) ==== Manipulations and Transformations ==== {{https://web.archive.org/web/20110805035356/http://bobpowell.net/images/srts.gif?300}} * translate() - Specify a translation offset in the x and y directions * rotate() - Specify an angle of rotation in radians * shear() - Specify a shearing factor in the x and y directions {{http://root.cern.ch/TaligentDocs/TaligentOnline/DocumentRoot/1.0/Docs/books/GS/GS102GS2.DOC_AFrame_5.gif?300}} * scale() - Specify a scaling factor in the x and y directions ==== Moving Pictures ==== * Whether it's this: * {{http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/media/spaceinvaders.gif}} * ... or this: * {{http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/media/Minesweeper_0.gif}} -> {{http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/media/Minesweeper_flag.gif}} * After you've done your painting through paint() or paintComponent() * Repaint: * repaint() - Force repainting on the screen. * repaint() causes paintComponent() to be called for all components. ==== Drawing Images (external images, e.g. gif, png, jpg) ==== * Need, at the very least, java.awt.image.* (Image class (AWT)) * drawImage(Image img, int x, int y, ImageObserver observer) ---- ===== Code Samples ===== * [[http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/labs/ui2d/drawLine.java|Draw a red line]] (add code to draw more shapes at different locations) * [[http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/labs/ui2d/moveLine.java|Drag a red line to paint a region]] * [[http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/labs/ui2d/DrawMario.java|Load and draw an external image file]] * [[http://rockhopper.monmouth.edu/~jchung/cs498gd/fa15/labs/ui2d/moveStringKb.java|Use keyboard events to move a string around]] ---- ----