Chapter 16


Exercise 1 Write a program that displays a frame. The frame's paint() method should draw something simple. The application should also maintain a count of the number of times paint() is called. This count should be printed out every time paint() is called. Execute your application, and use it to help determine whether paint() is called when:

The application starts up.

The frame is minimized/iconified.

The frame is restored to normal size after being minimized/iconified.

The frame is restored to normal size after being minimized/iconified.

The frame is moved.

The frame is partially covered by another frame.

The frame is uncovered.

Solution 1 The following code prints a message whenever paint() is called:

import java.awt.*; public class Ch16Q1 extends Frame {   int   nCallsToPaint;   Ch16Q1()   {     setSize(300, 300);   }   public void paint(Graphics g)   {     g.setColor(Color.cyan);     g.drawLine(100, 100, 200, 200);     nCallsToPaint++;     System.out.println(nCallsToPaint +                        " calls to paint()");   }   public static void main(String[] args)   {     (new Ch16Q1()).setVisible(true);   } }

The paint() method is called when the application starts up, and when it is restored after being minimized/iconified. It is also called when the frame is uncovered. It is not called when the frame is moved. Depending on your system, it may or may not be called when the frame is covered.

Exercise 2 Every Java thread is represented by an instance of the java.lang.Thread class. You can get a reference to the currently running thread by calling the currentThread() static method of the Thread class. Threads have names. The class has a method called getName(), which returns the name as a string. So you can print out the name of the current thread by calling

System.out.println(Thread.currentThread().getName());

Write a simple frame application that makes this call in its main() method and in its paint() method. Verify that main()and paint() are executed in different threads.

Solution 2 The following application prints the name of the current thread in main() and paint():

import java.awt.*; public class Ch16Q2 extends Frame {   Ch16Q2()   {     setSize(300, 300);   }   public void paint(Graphics g)   {     g.setColor(Color.cyan);     g.drawLine(100, 100, 200, 200);     System.out.println("paint() thread is called:");     System.out.println(Thread.currentThread().getName());   }   public static void main(String[] args)   {     System.out.println("main() thread is called:");     System.out.println(Thread.currentThread().getName());     (new Ch16Q2()).setVisible(true);   } }

Exercise 3 Write an application that adds the same action listener to a button twice. For example, if myButton is the button and myListener is the action listener, your code would contain the following lines:

myButton.addActionListener(myListener); myButton.addActionListener(myListener);

Your listener's actionPerformed() method should print out a message to tell you that it got called. If you press the button once, do you expect the message to be printed out once or twice? Run your application to see if you guessed right.

Of course, in real life there would never be a good reason for doing this. But you might do it by accident. For example, you might paste the line into your source code twice by accident. So it's good to know in advance what the symptom will be, so that you can recognize it and fix the problem if it ever comes up.

Solution 3 Here is the listener class:

import java.awt.event.*; class Aclis implements ActionListener {   public void actionPerformed(ActionEvent e)   {     System.out.println("actionPerformed() was called.");   }

And here is the application class:

import java.awt.*; public class Ch16Q3 extends Frame {   Ch16Q3()   {     setLayout(new FlowLayout());     Button btn = new Button("Push Me");     Aclis ac = new Aclis();     btn.addActionListener(ac);     btn.addActionListener(ac);     add(btn);     setSize(300, 300);   }   public static void main(String[] args)   {     (new Ch16Q3()).setVisible(true);   } }

When you push the button, the message is printed out twice.

Exercise 4 Suppose a class has an actionPerformed() method, as specified by the ActionListener interface, but the class does not state that it implements the interface. Can an instance of the class be used as a button's action listener?

Solution 4 The following class contains an actionPerformed() method, but it does not declare that it implements the ActionListener interface:

import java.awt.event.*; class NotAnActionListener {   public void actionPerformed(ActionEvent e)   {     System.out.println("actionPerformed() was called.");   } }

Since the class has the right kind of method, you might be tempted to use it as an action listener:

. . . Button btn = new Button("OK"); NotAnActionListener naal = new NotAnActionListener(); btn.addActionListener(naal); . . .

This code will not compile. For a class to be eligible to be an action listener, it is not enough for it to provide an actionPerformed() method, because that alone does not mean that it implements the ActionListener interface .

Exercise 5 Run Nim Lab by typing java events.NimLab. Select Disable Buttons..... and play the game. This version is the result of three rounds of improvements made to the original program. What additional improvements can you suggest? Think about how the game could be modified to make the GUI easier and more natural.

Solution 5 Here are some possible improvements:

  • Add a Restart button.

  • Provide notification when a player wins.

  • Eliminate the buttons. Players would click on a coin to remove it. This would provide direct manipulation of the coins, rather than the indirect manipulation that the buttons provide.

Do you have any other ideas? E-mail them to groundupjava@sgsware.com, and they might be included in the next revision of this book (with your name mentioned).

Exercise 6 The various event classes (ActionEvent, ItemEvent, etc.) all inherit the getSource() method from a superclasss. Use the API pages to determine the name of that superclass.

Solution 6 java.util.EventObject.

Exercise 7 Write an application with a GUI that contains a choice and a text area. When the choice is activated, a message should be written to the text area, stating the choice's selected index.

Suggested design: Your frame should contain a panel (at North) that contains the choice. The text area should be at South. If you need a guideline, the TextAreaNim program in the "Improving the GUI" section has a similar structure.

Solution 7 Here's the code:

import java.awt.*; import java.awt.event.*; public class Ch16Q7 extends Frame implements ItemListener {   private Choice    choice;   private TextArea  ta;   Ch16Q7()   {     Panel pan = new Panel();     choice = new Choice();     choice.add("Dragons");     choice.add("Centaurs");     choice.add("Unicorns");     choice.add("Manticores");     choice.addItemListener(this);     pan.add(choice);     add(pan, "North");     ta = new TextArea(40, 20);     add(ta, "Center");     setSize(300, 200);   }   public void itemStateChanged(ItemEvent e)   {     ta.append("You chose " +               choice.getSelectedIndex() +               "\n");   }   public static void main(String[] args)   {     (new Ch16Q7()).setVisible(true);   } }

The following illustration shows the GUI for Exercise 7.

Exercise 8 Write an application with a GUI that contains a text field and a text area. When the user presses the Enter key in the text field, the text field's contents should be copied into text area, followed by a newline character.

Your event-handling code will need to retrieve the contents of the text field. You do that by calling the text field's getText() method, which returns a string.

Suggested design: Your frame should contain a panel at North that contains the text field. The text area should go at Center.

Solution 8 Here's the code:

import java.awt.*; import java.awt.event.*; public class Ch16Q8extends Frame implements ActionListener {   private TextField    tf;   private TextArea     ta;   Ch16Q8()   {     Panel pan = new Panel();     tf = new TextField("Type Here            ");     tf.addActionListener(this);     pan.add(tf);     add(pan, "North");     ta = new TextArea(40, 20);     add(ta, "Center");     setSize(300, 200);   }   public void actionPerformed(ActionEvent e)   {     ta.append(tf.getText() + "\n");   }   public static void main(String[] args)   {     (new Ch16Q8()).setVisible(true);   } }

The following illustration shows the GUI for Exercise 8.




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net