Sunday 26 March 2017

Creating a Windowed Program & Working with Graphics - Java Tutorials

Creating a Windowed Program

Although creating applets is the most common use for Java’s AWT, it is possible to create stand-alone AWT-based applications, too. To do this, simply create an instance of the window or windows you need inside main( ). For example, the following program creates a frame window that responds to mouse clicks and keystrokes:

  // Create an AWT-based application.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;

  // Create a frame window.
  public class AppWindow extends Frame {
    String keymsg = "This is a test.";
    String mousemsg = "";
    int mouseX=30, mouseY=30;

    public AppWindow() {
      addKeyListener(new MyKeyAdapter(this));
      addMouseListener(new MyMouseAdapter(this));
      addWindowListener(new MyWindowAdapter());
    }

    public void paint(Graphics g) {
      g.drawString(keymsg, 10, 40);
      g.drawString(mousemsg, mouseX, mouseY);
    }

    // Create the window.
    public static void main(String args[]) {
      AppWindow appwin = new AppWindow();

      appwin.setSize(new Dimension(300, 200));
      appwin.setTitle("An AWT-Based Application");
      appwin.setVisible(true);
    }
  }

  class MyKeyAdapter extends KeyAdapter {
    AppWindow appWindow;
    public MyKeyAdapter(AppWindow appWindow) {
      this.appWindow = appWindow;
    }
    public void keyTyped(KeyEvent ke) {
      appWindow.keymsg += ke.getKeyChar();
      appWindow.repaint();
    };
  }

  class MyMouseAdapter extends MouseAdapter {
    AppWindow appWindow;
    public MyMouseAdapter(AppWindow appWindow) {
      this.appWindow = appWindow;
    }
    public void mousePressed(MouseEvent me) {
      appWindow.mouseX = me.getX();
      appWindow.mouseY = me.getY();
      appWindow.mousemsg = "Mouse Down at " + appWindow.mouseX +
                           ", " + appWindow.mouseY;
      appWindow.repaint();
    }
  }

  class MyWindowAdapter extends WindowAdapter {
    public void windowClosing(WindowEvent we) {
      System.exit(0);
    }
  }

Once created, a frame window takes on a life of its own. Notice that main( ) ends with the call to appwin.setVisible(true). However, the program keeps running until you close the window. In essence, when creating a windowed application, you will use main( ) to launch its top-level window. After that, your program will function as a GUI-based application, not like the console-based programs used earlier.


Displaying Information Within a Window

In the most general sense, a window is a container for information. Although we have already output small amounts of text to a window in the preceding examples, we have not begun to take advantage of a window’s ability to present high-quality text and graphics. Indeed, much of the power of the AWT comes from its support for these items. For this reason, the remainder of this chapter discusses Java’s text-, graphics-, and font-handling capabilities. As you will see, they are both powerful and flexible.




Working with Graphics

The AWT supports a rich assortment of graphics methods. All graphics are drawn
relative to a window. This can be the main window of an applet, a child window of
an applet, or a stand-alone application window. The origin of each window is at the
top-left corner and is 0,0. Coordinates are specified in pixels. All output to a window
takes place through a graphics context. A graphics context is encapsulated by the
Graphics class and is obtained in two ways:
  • It is passed to an applet when one of its various methods, such as paint( ) or update( ), is called.
  • It is returned by the getGraphics( ) method of Component.

For the remainder of the examples in this chapter, we will be demonstrating graphics in the main applet window. However, the same techniques will apply to any other window.

The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the currently selected graphics color, which is black by default. When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped. Let’s take a look at several of the drawing methods.


Drawing Lines

Lines are drawn by means of the drawLine( ) method, shown here:

      void drawLine(int startX, int startY, int endX, int endY)

drawLine( ) displays a line in the current drawing color that begins at startX,startY and ends at endX,endY.

The following applet draws several lines:

  // Draw lines
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="Lines" width=300 height=200>
  </applet>
  */
  public class Lines extends Applet {
    public void paint(Graphics g) {
      g.drawLine(0, 0, 100, 100);
      g.drawLine(0, 100, 100, 0);
      g.drawLine(40, 25, 250, 180);
      g.drawLine(75, 90, 400, 400);
      g.drawLine(20, 150, 400, 40);
      g.drawLine(5, 290, 80, 19);
    }
  }


Drawing Rectangles

The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively. They are shown here:

      void drawRect(int top, int left, int width, int height)
      void fillRect(int top, int left, int width, int height)

The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by width and height. To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:

      void drawRoundRect(int top, int left, int width, int height,
                                          int xDiam, int yDiam)

      void fillRoundRect(int top, int left, int width, int height,
                                      int xDiam, int yDiam)

A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by width and height. The diameter of the rounding arc along the X axis is specified by xDiam. The diameter of the rounding arc along the Y axis is specified by yDiam.

The following applet draws several rectangles:

  // Draw rectangles
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="Rectangles" width=300 height=200>
  </applet>
  */
  
  public class Rectangles extends Applet {
    public void paint(Graphics g) {
      g.drawRect(10, 10, 60, 50);
      g.fillRect(100, 10, 60, 50);
      g.drawRoundRect(190, 10, 60, 50, 15, 15);
      g.fillRoundRect(70, 90, 140, 100, 30, 40);
    }
  }


Drawing Ellipses and Circles

To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods are shown here:

      void drawOval(int top, int left, int width, int height)
      void fillOval(int top, int left, int width, int height)

The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top,left and whose width and height are specified by width and height. To draw a circle, specify a square as the bounding rectangle.

The following program draws several ellipses:

  // Draw Ellipses
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="Ellipses" width=300 height=200>
  </applet>
  */
  
  public class Ellipses extends Applet {
    public void paint(Graphics g) {
      g.drawOval(10, 10, 50, 50);
      g.fillOval(100, 10, 75, 50);
      g.drawOval(190, 10, 90, 30);
      g.fillOval(70, 90, 140, 100);
    }
  }


Drawing Arcs

Arcs can be drawn with drawArc( ) and fillArc( ), shown here:

      void drawArc(int top, int left, int width, int height, int startAngle,
                              int sweepAngle)

      void fillArc(int top, int left, int width, int height, int startAngle,
                          int sweepAngle)
                         
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose width and height are specified by width and height. The arc is drawn from startAngle through the angular distance specified by sweepAngle. Angles are specified in degrees. Zero degrees is on the horizontal, at the three o’clock position. The arc is drawn counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is negative. Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle would be 90 and the sweep angle 180.

The following applet draws several arcs:

  // Draw Arcs
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="Arcs" width=300 height=200>
  </applet>
  */

  public class Arcs extends Applet {
    public void paint(Graphics g) {
      g.drawArc(10, 40, 70, 70, 0, 75);
      g.fillArc(100, 40, 70, 70, 0, 75);
      g.drawArc(10, 100, 70, 80, 0, 175);
      g.fillArc(100, 100, 70, 90, 0, 270);
      g.drawArc(200, 80, 80, 80, 0, 180);
    }
  }


Drawing Polygons

It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ), shown here:

      void drawPolygon(int x[ ], int y[ ], int numPoints)
      void fillPolygon(int x[ ], int y[ ], int numPoints)

The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The number of points defined by x and y is specified by numPoints. There are alternative forms of these methods in which the polygon is specified by a Polygon object. 

The following applet draws an hourglass shape:

  // Draw Polygon
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="HourGlass" width=230 height=210>
  </applet>
  */

  public class HourGlass extends Applet {
    public void paint(Graphics g) {
      int xpoints[] = {30, 200, 30, 200, 30};
      int ypoints[] = {30, 30, 200, 200, 30};
      int num = 5;

      g.drawPolygon(xpoints, ypoints, num);
    }
  }


Sizing Graphics

Often, you will want to size a graphics object to fit the current size of the window in which it is drawn. To do so, first obtain the current dimensions of the window by calling getSize( ) on the window object. It returns the dimensions of the window encapsulated within a Dimension object. Once you have the current size of the window, you can scale your graphical output accordingly.

To demonstrate this technique, here is an applet that will start as a 200×200-pixel square and grow by 25 pixels in width and height with each mouse click until the applet gets larger than 500×500. At that point, the next click will return it to 200×200, and the process starts over. Within the window, a rectangle is drawn around the inner border of the window; within that rectangle, an X is drawn so that it fills the window. This applet works in appletviewer, but it may not work in a browser window.

  // Resizing output to fit the current size of a window.
  import java.applet.*;
  import java.awt.*;
  import java.awt.event.*;
  /*
    <applet code="ResizeMe" width=200 height=200>
    </applet>
  */

  public class ResizeMe extends Applet {
    final int inc = 25;
    int max = 500;
    int min = 200;
    Dimension d;

    public ResizeMe() {
      addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent me) {
          int w = (d.width + inc) > max?min :(d.width + inc);
          int h = (d.height + inc) > max?min :(d.height + inc);
          setSize(new Dimension(w, h));
        }
      });
    }
    public void paint(Graphics g) {
      d = getSize();

      g.drawLine(0, 0, d.width-1, d.height-1);
      g.drawLine(0, d.height-1, d.width-1, 0);
      g.drawRect(0, 0, d.width-1, d.height-1);
    }
  }

No comments:

Post a Comment