Skip to main content

more options

Writing your own subclass of JFrame

It is important that you practice writing Java classes, and methods within them, especially in the beginning. Below, we provide some simple exercises in creating subclasses of class JFrame, as done in the topic 2 of Module 1, part 6. Do two or three of them —or more, until they become easy to do.

Page 36 of Gries/Gries contains a list of JFrame methods that you can use.

Remember to write suitable specifications of the methods that you write!

1. A subclass to swap width and height

In DrJava, write a subclass named JFrameFun of class JFrame. Put in it a procedure swapHtAndWdth to swap the width and height of the window. Test it in the DrJava's interactions pane by creating an instance of JFrameFun, showing it by calling its procedure show, dragging the window to change its size, and then calling method swapHtAndWdth.

2. Add procedures to double and halve the width

In class JFrameFun of exercise 1, define a procedure that doubles the width of the window and another that halves the width of the window. Test the procedures in the interactions pane. How small can you make the width? Is there a lower bound on the width of the window?

3. Put the date and time in the title

Add a procedure setTitleToDate to class JFrameFun of exercise 1 (or 2) that will put the date and time in the title of the window. Below, we show you how.

This expression creates an object of class Date, which contains the time at which the object was created:

new java.util.Date()

This object has a function toString, which provides the date and time as a String. Try this in the interactions pane to see what happens:

(new java.util.Date()).toString()

Do it several times, and watch the time change.

Now, write procedure setTime. Its body should call procedure setTitle with the proper argument.

4. Put the position in the title

You know how to get the position (x, y) of the top-left pixel of the window. Write a procedure putPositionInTitle that will put this position in the title. If the position is (5, 6), you might want the title to say something like "window is at (5, 6)". Once you have written the title, drag the window around to various places; after each drag, call procedure putPositionInTitle.

5. Switch position and size

Write a method swap that swaps the position and size of the window. For example, if the window is currently at position (200, 300) and has size (60,40), then change the position to (60,40) and make the size (200, 300). To do this, you will have to declare local variables within the body of the procedure to save values. For example, you can write

int w= getWidth();

as the first statement of the procedure body. Test your procedure.

Answers

The answers are in this java file.