Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Chapter 2. (Introduction) Swing Mechanics. Easy for reading, Click here!

Custom Search
Chapter 2. (Introduction) Swing Mechanics. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 9/14 



Previous Page Previous Page (8/14) - Next Page (10/14) Next Page
Subpages: 1. JComponent properties, size, and positioning 
2.  Event handling and dispatching 
3. Multithreading
4. Timers
5. AppContext service
6. Inside Timers & the TimerQueue
7. JavaBeans architecture
8. Fonts, Colors, Graphics and text
9. Using the Graphics clipping area
10. Graphics debugging
11. Painting and validation
12. Focus Management
13. Keyboard input, KeyStrokes, and Actions
14. SwingUtilities

2.9    Using the Graphics clipping area

We can use the clipping area to optimize component rendering. This may not noticably improve rendering speed for simple components such as our JCanvas above, but it is important to understand how to implement such functionality, as Swing's whole painting system is based on this concept (we will find out more about this in the next section).

We now modify JCanvas so that each of our shapes, strings, and images is only painted if the clipping area intersects its bounding rectangular region. (These intersections are fairly simple to compute, and it may be helpful for you to work through, and verify each one.) Additionaly, we maintain a local counter that is incremented each time one of our items is painted. At the end of the paintComponent() method we display the total number of items that were painted. Below is our optimized JCanvas paintComponent() method (with counter):

The Code: JCanvas.java

see \Chapter1\3

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    // counter

    int c = 0;

    // for use below

    int w = 0;

    int h = 0;

    int d = 0;

    // get damaged region

    Rectangle r = g.getClipBounds();

    int clipx = r.x;

    int clipy = r.y;

    int clipw = r.width;

    int cliph = r.height;

    // fill only damaged region only

    g.setColor(Color.white);

    g.fillRect(clipx,clipy,clipw,cliph);

    // filled yellow circle if bounding region has been damaged

    if (clipx <= 240 && clipy <= 240) {

      g.setColor(Color.yellow);

      g.fillOval(0,0,240,240); c++;

    }

    // filled magenta circle if bounding region has been damaged

    if (clipx + clipw >= 160 && clipx <= 400

        && clipy + cliph >= 160 && clipy <= 400) {

      g.setColor(Color.magenta);

      g.fillOval(160,160,240,240); c++;

    }

    w = m_flight.getIconWidth();

    h = m_flight.getIconHeight();

    // paint the icon below blue sqaure if bounding region damaged

    if (clipx + clipw >= 280-(w/2) && clipx <= (280+(w/2))

        && clipy + cliph >= 120-(h/2) && clipy <= (120+(h/2))) {

      m_flight.paintIcon(this,g,280-(w/2),120-(h/2)); c++;

    }

    // paint the icon below red sqaure if bounding region damaged

    if (clipx + clipw >= 120-(w/2) && clipx <= (120+(w/2))

        && clipy + cliph >= 280-(h/2) && clipy <= (280+(h/2))) {

      m_flight.paintIcon(this,g,120-(w/2),280-(h/2)); c++;

    }

    // filled transparent red square if bounding region damaged

    if (clipx + clipw >= 60 && clipx <= 180

        && clipy + cliph >= 220 && clipy <= 340) {

      g.setColor(m_tRed);

      g.fillRect(60,220,120,120); c++;

    }

    // filled transparent green circle if bounding region damaged

    if (clipx + clipw > 140 && clipx < 260

        && clipy + cliph > 140 && clipy < 260) {

      g.setColor(m_tGreen);

      g.fillOval(140,140,120,120); c++;

    }

    // filled transparent blue square if bounding region damaged

    if (clipx + clipw > 220 && clipx < 380

        && clipy + cliph > 60 && clipy < 180) {

      g.setColor(m_tBlue);

      g.fillRect(220,60,120,120); c++;

    }

    g.setColor(Color.black);

    g.setFont(m_biFont);

    FontMetrics fm = g.getFontMetrics();

    w = fm.stringWidth("Swing");

    h = fm.getAscent();

    d = fm.getDescent();

    // Bold, Italic, 36-point "Swing" if bounding regiondamaged

    if (clipx + clipw > 120-(w/2) && clipx < (120+(w/2))

        && clipy + cliph > (120+(h/4))-h && clipy < (120+(h/4))+d)

    {

      g.drawString("Swing",120-(w/2),120+(h/4)); c++;

    }

    g.setFont(m_pFont);

    fm = g.getFontMetrics();

    w = fm.stringWidth("is");

    h = fm.getAscent();

    d = fm.getDescent();

    // Plain, 12-point "is" if bounding region damaged

    if (clipx + clipw > 200-(w/2) && clipx < (200+(w/2))

        && clipy + cliph > (200+(h/4))-h && clipy < (200+(h/4))+d)

    {

      g.drawString("is",200-(w/2),200+(h/4)); c++;

    }

    g.setFont(m_bFont);

    fm = g.getFontMetrics();

    w = fm.stringWidth("powerful!!");

    h = fm.getAscent();

    d = fm.getDescent();

    // Bold 24-point "powerful!!" if bounding region damaged

    if (clipx + clipw > 280-(w/2) && clipx < (280+(w/2))

        && clipy + cliph > (280+(h/4))-h && clipy < (280+(h/4))+d)

    {

      g.drawString("powerful!!",280-(w/2),280+(h/4)); c++;

    }

    System.out.println("# items repainted = " + c + "/10");

  }

Try running this example and dragging another window in your desktop over parts of the JCanvas. Keep your console in view so that you can monitor how many items are painted during each repaint. Your output should be displayed something like the following (of course you'll probably see different numbers):

# items repainted = 4/10

# items repainted = 0/10

# items repainted = 2/10

# items repainted = 2/10

# items repainted = 1/10

# items repainted = 2/10

# items repainted = 10/10

# items repainted = 10/10

# items repainted = 8/10

# items repainted = 4/10

Optimizing this canvas wasn't that bad, but imagine how tough it would be to optimize a container with a variable number of children, possibly overlapping, with double-buffering options and transparency. This is what JComponent does, and it does it quite efficiently. We will learn a little more about how this is done in section 2.11. But first we'll finish our high level overview of graphics by introducing a very powerful and well-met feature new to Swing: graphics debugging.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy