Java Reference
In-Depth Information
Example 8−2: Command.java (continued)
/**
* This simple program demonstrates how a Command object can be parsed from
* a string and used as an ActionListener object in a Swing application.
**/
static class Test {
public static void main(String[] args) throws IOException {
javax.swing.JFrame f = new javax.swing.JFrame("Command Test");
javax.swing.JButton b1 = new javax.swing.JButton("Tick");
javax.swing.JButton b2 = new javax.swing.JButton("Tock");
javax.swing.JLabel label = new javax.swing.JLabel("Hello world");
java.awt.Container pane = f.getContentPane();
pane.add(b1, java.awt.BorderLayout.WEST);
pane.add(b2, java.awt.BorderLayout.EAST);
pane.add(label, java.awt.BorderLayout.NORTH);
b1.addActionListener(Command.parse(label, "setText(\"tick\");"));
b2.addActionListener(Command.parse(label, "setText(\"tock\");"));
f.pack();
f.show();
}
}
}
Exercises
8-1. Write a program that takes the name of a Java class as a command-line argu-
ment and uses the Class class to print out all the superclasses of that class.
For example, if invoked with the argument “java.awt.Applet”, the program
prints the following: java.lang.Object java.awt.Component java.awt.Con-
tainer java.awt.Panel .
8-2. Modify the program you wrote in Exercise 8-1 so that it prints out all inter-
faces implemented by a specified class or by any of its superclasses. Check
for the case of classes that implement interfaces that extend other interfaces.
For example, if a class implements java.awt.LayoutManager2 , the LayoutMan-
ager2 interface and LayoutManager , its superinterface, should be listed.
8-3. Define a class named Assignment that is modeled on the Command class shown
in Example 8-2. Instead of invoking a named method, as Command does,
Assignment should assign a value to a named field of an object. Give your
class a constructor with the following signature:
public Assignment(Object target, Field field, Object value)
Also give it an assign() method that, when invoked, assigns the specified
value to the specified field of the specified object. Assignment should imple-
ment ActionListener and define an actionPerformed() method that also
performs the assignment. Write a static parse() method for Assignment that is
similar to the parse() method of Command . It should parse strings of the form
fieldname = value and be able to parse boolean, numeric, and string values.
Search WWH ::




Custom Search