Docsity

Java Graphics: Painting Swing Components and Primitives, Slides of Web Design and Development

Partial preview of the text

Download Java Graphics: Painting Swing Components and Primitives and more Slides Web Design and Development in PDF only on Docsity!

Web Design & Development

Lecture 18

Java Graphics

MyApp

Open WinExp, Notepad

Desktop gets repaint event

MyApp gets repaint event

MyApp JPanel gets repaint event

Painting a Swing Component

  • Three methods are at the heart of painting a

swing component

  • paintComponent()
  • paintBorder()
  • paintChildren()

The Swing Painting Methods

  • It's one of three methods, that objects of type

JComponent use to paint themselves. The three methods

are invoked in this order:

  • paintComponent โ€” The main method for painting. By default, it first paints the background. Then it performs any custom painting.
  • paintBorder โ€” Tells the component's border (if any) to paint. Do not invoke or override this method.
  • paintChildren โ€” Tells any components contained by this component to paint themselves. Do not invoke or override this method Docsity.com
  • An Example of Painting
  • To illustrate painting, we'll use the

swingApplication program. Here is its GUI:

Your Painting Strategy

  • Steps
    • Subclass JPanel
      • class MyPanel extends JPanel
    • Override the paintComponent(Graphics g) method
      • Inside method using graphics object Do whatever drawing you want to do
    • Install that JPanel inside a JFrame
      • When frame becomes visible through the paintChildren() method your panel become visible
      • To become visible your panel will call paintComponent() method which will do your custom drawing Docsity.com

Example Code: Test1.java

import javax.swing.; import java.awt.; public class Test1{ JFrame f; MyPan1 p; public Test1(){ f = new JFrame(); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); p = new MyPan1(); c.add(p); f.setSize(400,400); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // end constructor**

Example Code: Test1.java

public static void main(String args[ ]){ Test1 t = new Test1(); }

} // end class

Graphics Primitives

Draw Fill

  • Point (x,y)
  • Line (pt1,pt2)
  • PolyLine (pt list)
  • Arc
  • Oval (pt, w,h)
  • Rectangle (pt, w,h)
    • RoundRectangle
  • Polygon (pt list)
  • Image (file, x,y)
  • Text (string, x,y) (^) label

Graphics Attributes

  • Color
  • Font
  • Stroke attributes:
    • Line width, dash, end caps, joins, miter
  • Paint attributes:
    • Color, gradient, texture
  • Composite:
    • Blending
  • Transforms:
    • Translate, rotate, flip, shear, scale