Swing and AWT

Graphics and graphical user interfaces are programmed using java.awt and javax.swing packages.

Components

Here's a simplified class diagram of the swing package:

Notes

·        The desktop window is a JPanel surrounded by a JFrame.

·        When the desktop window appears on the desktop it runs inside of a user interface thread that listens for user input.

·        Here's a simple example: AppPanel.java

Events

Controls (JButton, JTextField, JMenuItem, etc.) publish action events when selected/clicked/touched/etc. Programmer-defined controllers implement the ActionListener interface and subscribe to any controls they are interested in. When that control fires an action event, the controller's implementation of actionPerformed is automatically called. This method typically updates the application's model in some way.

Layout

Programmers can set the layout strategy used by JPanel's add component method:

Notes

·        JPanels can be nested. This allows programmers to use different layout strategies in different regions.

·        GridLayout allows us to divide a JPanel into an N x M grid of components. FlowLayout tries to center-align components as they are added. BorderLayout divides a JPanel into North, East, South, West, and Center regions.

Graphics

Every time the operating system decides a window needs to be redrawn, it calls the paintComponent method of every component contained in the desktop window. The paintComponent method paints a picture of the component in the window.

We can override paintComponent. For example:

class DemoComponent extends JComponent {

   public void paintComponent(Graphics gc) {
      Color oldColor = gc.getColor();
      gc.setColor(Color.RED);
      gc.fillRect(10, 20, 200, 100);
      gc.setColor(Color.BLUE);
      gc.fillOval(50, 50, 100, 100);
      gc.setColor(oldColor); // be polite!
   }
}

Remember, the operating system will call this method, not the program. The operating system will supply the input, gc, a graphical context. A graphical context is like a virtual artist's studio. It contains a palette of colors, a pen to draw lines, a brush to paint regions, stencils to draw shapes, and a blank canvas with a coordinate system:

http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/j2se/intro/lectures/graphics_files/image002.gif

To make all of these things work we need the following import statements:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

Here's how the window looks when it's displayed:

http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/j2se/intro/lectures/graphics_files/image004.jpg

Programmers can request that the operating system calls paintComponent by calling the component's repaint method.

References

Full details can be found here:

·        Java Foundation Classes