Frames in JAVA: Opening A Window
Frames in JAVA: Opening A Window
Opening a Window
So far, we've just written programs that run right from the shell, taking text input from the
keybord and outputting text to the shell window. Most programs won't work like this and will
instead open their own window. A simple Java object to use is Frame, in the java.awt package.
The basic Frame object has methods for doing things, but a default constructor that doesn't draw
anything, not even an empty frame. To make a Frame that does something we use the extends
keyword like so:
import java.awt.*;
public class FrameTest extends Frame
{
// here goes the extra stuff FrameTest does or has
// that Frame doesn't
}
This means that every FrameTest is a Frame, and so has everything a Frame has and possibly
more, and is everything a Frame is and possibly more. Below is a sample FrameTest that has two
integers to represent its width and height and performs three functions:
A Sample Frame
import java.awt.*;
import java.awt.event.*;
public class FrameTest extends Frame
{
private int w = 400,
h = 300;
// ctor that does something
// (overrides do-nothing Frame ctor)
public FrameTest()
{
super("FrameTest"); // call Frame ctor, telling what to label the
frame
// without this, you won't be able to close the frame
this.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e ) { System.exit(0); }
});
setBackground( Color.black );
setSize(w,h);
show();
The Graphics object has basic methods for doing things like drawing lines, rectangles and ovals
(which includes circles, of course), as well as drawing text. Here are some of them:
setColor(Color c)
used to set the current Color for drawing. There are some Color constants you can use,
like Color.red, or you can specify the red, green and blue of the color in the range 0-255,
like setColor(new Color(0,128,128)) for a dull cyan. Look at the description of the Color
class for more details on colors.
drawLine(int x1, int y1, int x2, int y2)
draw a line from (x1,y1) to (x2,y2) using the current color
drawString(String str, int x1, int y1)
draw the text given by str with the graphics context's current color and font
drawRect(int x, int y, int width, int height)
draw a rectangle whose upper left corner is at (x,y) and whose width and height are as
given
drawOval(int x, int y, int width, int height)
draw an oval bounded by the rectangle whose upper left corner is at (x,y) and whose
width and height are as given