HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

The past three articles in this series have highlighted the strengths of scripting languages. They're interactive and dynamic, and allow you to experiment, debug and prototype solutions quickly. However, the most common response when I speak to die-hard Java fanatics is, "Yeah, but I'll have to learn another language and I already know Java" (I consider myself a die-hard Java fanatic to a degree).

To be honest, this is a barrier that most won't cross. But what if you could have the best of both worlds? What if you could have your cake and eat it too?

Well, in a sense you can. You can use a Java-like scripting language. Now when I say that, most of you were probably thinking JavaScript. (Admit it.) But I'm not talking about JavaScript.

Java and JavaScript have a similar syntax, both deriving from C/C++. However, the way that JavaScript defines methods, event handlers and classes is quite different from Java. In fact, other than the similar names and common C heritage, JavaScript and Java have little in common. (Consider the inheritance by prototype model by JavaScript versus the more common inheritance model found in Java. However, Rhino is a good marriage of Java and JavaScript. )

If you know Java, learning JavaScript syntax will take a while, but not too long. However, you don't have to learn another syntax to get the advantages of a dynamic scripting language. Several scripting languages are heavily based on the Java syntax.

Two of the most popular, BeanShell and DynamicJava, are interpreted versions of Java. Both have interactive interpreters that allow experimenting with Java APIs. Both closely follow the Java syntax. (DynamicJava is much closer.)

BeanShell Background
BeanShell is a Java source interpreter with object scripting language features. In addition to some scripting commands, BeanShell executes standard Java statements. As stated earlier, this gives BeanShell an advantage over scripting languages like JPython and NetRexx because Java programmers can learn it quickly.

One advantage of BeanShell over plain Java is you can use BeanShell interactively for Java experimentation and debugging. BeanShell, which is easy to embed, can be used as a scripting engine for your applications. Not surprisingly, the author of BeanShell compares the relationship of Java and BeanShell to the relationship of C and Tcl/TK.

The name BeanShell has always kind of thrown me for a loop. When I first looked into it (almost two years ago), the name made me think of C Shell or KornShell, command interpreters (shells) for the UNIX world. Somehow the name seems to be related to shell scripting, although BeanShell has little to do with KornShell and more to do with Python, Perl and Tcl. That said, BeanShell does have some UNIX-like shell commands as follows: cd(), cat(), dir(), pwd(), rm(), exec(), and so on.

Unlike DynamicJava, BeanShell supports scripted objects as simple method closures like those in JavaScript (see Part 1 of this series [Vol. 5, issue 2] for examples of JavaScript method closure). DynamicJava uses the Java syntax for adding methods to a class.

BeanShell closely mimics the Java language. For example, it uses the full Java statements and expressions syntax. It emulates strongly typed variables and methods. It mimics Java operators (arithmetic, logical and bitwise). BeanShell could aptly be renamed little Java. It closely follows the syntax of the language in many respects. It also adds features that are essential to a scripting language. For example, it allows dynamically typed (untyped) variables. It has the following scripting features: methods with optionally loose typing of arguments and return values, scripted objects with JavaScript-like method closures, and scripted AWT/Swing event handlers. Like JPython, BeanShell has convenience syntax for working with JavaBean properties. It also has many utilities for working with beans, e.g., loading a bean (load) and saving a bean (save(bean)). In addition, BeanShell has simplified ways for working with primitive wrapper types and hashtables.

One BeanShell claim to fame is that it has such a small footprint - less than 150K.

DynamicJava Background
DynamicJava supports all features and syntax defined by the Java language, including class and inner class definition and multithreading. And it adds features that make scripting easier:

  • Statements can be written outside classes and methods in the top-level namespace.
  • Typing is dynamic.
  • There's more than one package.
  • Methods are defined outside classes.
  • Comments can begin with #.
Where BeanShell is a subset of Java with scripting features, DyamicJava is a superset of Java with scripting features. Dynamic Java can be found at www.inria.fr/koala/djava/. The focus on DynamicJava seems to be compatibility with Java. It boasts the full implementation of the Java language specification in interpreted mode.

Rosetta Stone Examples
For comparison, each BeanShell sample application will have a corresponding Java implementation. This article covers the following sample applications.

  • A simple class definition (and object creation)
  • A simple GUI application
  • A simple statistics application
  • Embedding of script in an application (if applicable)
Before we go into the first example let's cover the basics of BeanShell. If you haven't installed it, please follow the directions in the next section.

Installing BeanShell
To install BeanShell go to www.beanshell.org/download.html. On this page are two options: BeanShell with the Utilities and Shell commands (the deluxe) and the core interpreter version (regular). When I go to a carwash I always order the deluxe version. I may not need an undercarriage wash, but why take chances? For BeanShell you should download the deluxe version because you can use the utilities to learn BeanShell. The deluxe version is bsh-1.0.jar.

Thus, to set up the classpath, you can do the following:

UNIX: export CLASSPATH=$CLASSPATH: usr/rickh/BeanShell/bsh- 1.0.jar

Windows: set classpath=%classpath%;c:\BeanShell\bsh-1_0.jar

If you're using a version of Java that doesn't include Swing, you need to add the swingall JAR file to the classpath as well. Some of the BeanShell utilities use Swing. Once you set up the classpath, you can start BeanShell in a graphical interactive interpreter or a console interactive interpreter.

To start BeanShell in a GUI interactive interpreter, do this:

java bsh.Console

or run as text-only on the command line:

java bsh.Interpreter

The graphical interpreter isn't that graphical.
BeanShell doesn't have an install package. However, installing and getting it up and running was brain-dead easy (just the way I like it). The directions are easy, and if you know Java well it won't be a problem to set up the environment to run it.

BeanShell 101: A Simple "Class"
BeanShell doesn't have classes like Java, JPython, NetRexx, C++ and so on. Instead, it allows object construction via nested methods similar to the way JavaScript and Perl define "classes." Although not classes per se, they have a similar effect, that is, they enable you to create objects or instances of the "class."

The example below defines an Employee "class" in BeanShell:

Employee (){
String firstName, lastName;
...
manager = null;

__init(){
super.firstName = "John";
...
}
return this;
}

For comparison, the equivalent Java Employee class would be defined as follows:

public class Employee{
private String firstName, lastName;
...

private Employee manager;

public Employee(){
firstName = "John";
...
}

...
}

Notice that the use of super in the BeanShell class isn't the same as it is in Java. In BeanShell it refers to the method that contains the current method. Thus super in the _init method refers to the Employee instance namespace - weird. Also notice that the manager variable in the BeanShell class is untyped, which means we can assign it later to any type. Compare the BeanShell Employee "class" in Listing 1 to roughly the equivalent Java class in Listing 2.

As you compare the two listings, notice that they both define toString methods. Also notice that, with the BeanShell "class," methods, arguments and return types don't have to be typed. Be sure to compare the getManager method in both the BeanShell version and the Java version.

To create an instance of an Employee and print it to the screen, you'd do the following:

print(Employee().toString());

The equivalent Java statement would be:

System.out.println(new Employee());

You can use Java objects in BeanShell, and if you use the Java Employee class in the BeanShell script, you can use the same syntax that you'd use in Java in BeanShell. Thus BeanShell allows you to do object composition with its Object scripting and to work with Java classes as you would in Java. The toString isn't recognized as a special method as it is in Java (for Object scripting).

Next we create two instances of employee called joe and ron and print those employees to the console. We print joe, who is ron's manager, by invoking the getManager method of ron - first in BeanShell, then in Java.

BeanShell:
joe = Employee();
joe.init("Joe", "Batista", 100, null, 1);
ron = Employee(); ron.init("Ron", "Furgeson", 101, joe, 1);
print(ron.toString());
print(ron.getManager().toString());

Java:
Employee joe = new Employee("Joe", "Batista", 100, null, 1);
Employee ron = new Employee("Ron", "Furgeson", 101, joe, 1);
System.out.println(ron);
System.out.println(ron.getManager());

As I said, the syntax is similar but not identical. Again, if you used a true Java Employee class, the code for Java and BeanShell would be identical. But I wanted to compare the way that BeanShell defines "classes" with the way that Java does.

A Simple GUI
Now that we've created a simple class, we'll create a simple GUI. I admit that the class and the GUI are nonsensical - the idea is to demonstrate the interactive nature of BeanShell.

If you have BeanShell installed, let's pretend we're prototyping this GUI. Fire up the interactive interpreter by typing java bsh.Console as the system prompt. (You can opt to follow along in the DynamicJava interactive interpreter; it should work out just as well.)

Import the JFrame from the javax.swing package.

bsh % import javax.swing.JFrame;

(Note that the bsh % is the BeanShell prompt, i.e., you don't need to type bsh % each time.)

Create an instance of the frame, set its size to 200 by 200 and make it visible. First create an instance.

bsh % frame = new JFrame("My Prototype");

There's a convenient way to set the frame's visible property. (Note that this can be used to set properties dynamically from a configuration file.)

bsh % frame{"visible"}=true;

You can also use the Java way to set the visible property to true.

bsh % frame.setVisible(true);

Now set the size of the frame to 200 by 200.

bsh % frame.setSize(200,200);

Note: If you remember the JPython article (JDJ, Vol. 5, issue 3), the foregoing three steps were done in one line of code.

In BeanShell any bean property of a class can be set wth the bean{"property_name"}=value syntax. By bean property I mean a property as defined by a getter and a setter method, that is, the bean "design pattern" for properties.

At this point all we have is a stupid-looking gray box. Let's add some components to it - some labels, text fields and an okay button. As we develop this GUI application, I'll point out some of the features of BeanShell. (Since this is a demo, we're not going to meet any GUI style guidelines.) First we need to import a few classes from javax.swing.

bsh % import javax.swing.JButton;
bsh % import javax.swing.JLabel;
bsh % import javax.swing.JTextField;
bsh % import javax.swing.JPanel;

We could have used the * syntax; for example, we could have said import javax.swing *; similar to the way you'd do it in Java.

Next, create a pane (JPanel instance) and add it to the frame. Before we do this let's invoke the show command, which will show us what is returned from expressions.

bsh % pane = new JPanel();
bsh % frame.getContentPane().add(pane);

The foregoing prints:

<javax.swing.JPanel[,0,0,0x0,invalid
layout=java.awt.FlowLayout,alignmentX=null
alignmentY=null,border=,flags=34
maximumSize=,minimumSize=,preferredSize=
defaultLayout=java.awt.FlowLayout[hgap=5,
vgap=5,align=center]]>

Now we want to add components to this pane using the GridBag layout. If this isn't familiar to you, it'll be good practice. First import the GridBag layout classes.

bsh % import java.awt.GridBagLayout;
bsh % import java.awt.GridBagConstraints;

Next, change the layout of the pane to an instance of GridBagLayout.

bsh % pane.setLayout(new GridBagLayout());

Now add the first component to the pane using a GridBagConstraint - a JLabel. This will use all of the default values of the GridBagConstraints (see Figure 1).

Figure 1
Figure 1:

bsh % GridBagConstraints constraint = new GridBagConstraints();
bsh % pane.add(new JLabel("Name"), constraint);
bsh % frame.validate();

Now add another JLabel, the label on the second row of the grid.

bsh % constraint.gridy=1;
bsh % pane.add(new JLabel("ID"), constraint);
bsh % frame.validate();

Add a text field on the first row in the second column. Then pack the frame (see Figure 2).

Figure 2
Figure 2:

bsh % name = new JTextField(25);
bsh % constraint.gridy=0;
bsh % constraint.gridx=1;
bsh % constraint.weightx=80.00;
bsh % pane.add(name, constraint);
bsh % frame.pack();

Now add a second text field for the employee ID, this time to the right on the second row. Then pack the frame.

bsh % id = new JTextField(10);
bsh % constraint.gridy=1;
bsh % pane.add(id, constraint);
bsh % frame.pack();

As you can see, this isn't what we want. The text field components are centered and look silly (see Figure 3). I forgot to align the text field to the left in their cells (not really - I forgot on purpose).

Figure 3
Figure 3:

Let's remove the components, then add them back with the proper alignment (see Figure 4). See how useful it is to be able to experiment with the layout in the interactive interpreter?

Remove the ID and name.

Figure 4
Figure 4:

bsh % pane.remove(id);
bsh % pane.remove(name);

Now add back the ID and name with the proper alignment.

bsh % constraint.anchor=GridBagConstraints.WEST; //anchor West
bsh % pane.add(id, constraint);
//add the id
bsh % constraint.gridy=0;
//set gridy for name
bsh % pane.add(name, constraint);
//add name
bsh % frame.pack();

The above demonstrates the interactive, experimental environment in BeanShell. You can explore the cause and effect without the normal recompile, retest environment. Also, you can do this in a very Java-like syntax so when you're ready to write the real version there won't be much conversion.

Bean events are easily handled in BeanShell. Just as with bean properties, BeanShell adds features to make event handling easier. To handle an event simply define the appropriately named method from the java.awt.event listener interface and register the corresponding "this" type reference with the component.

Unlike Java, the "this" keyword means current namespace and the "super" keyword means the encasing namespace. To demonstrate this, let's set up an okay button. When the okay button gets clicked, this prototype application will print out the employee's name and ID.

First create and add a button to the GUI (see Figure 5).

Figure 5
Figure 5:

bsh % okay = new JButton("Okay");
bsh % constraint.gridx=1;
bsh % constraint.gridy=2;
bsh %constraint.anchor=GridBagConstraints.CENTER;
bsh % pane.add(okay, constraint);
bsh % frame.pack();

Next, create a function. The function prints out the value of the name and ID text. Then register the current namespace with the okay button's actionListener.

bsh % actionPerformed( event ) {
print ("Name " + name.getText());
print ("ID " + id.getText());
}
bsh % okay.addActionListener(this);

Enter some text in the Name and ID field and hit the okay button. This is a simple session, creating a simple GUI. For those of you who followed along with BeanShell, let me know what you think of it. I'm new to BeanShell, but I like it.

Rosetta Stone GUI
The above was to show the interactive interpreter that comes with BeanShell. Now let's create a GUI based on the one we created above in both BeanShell and Java. In earlier articles we wrote the same GUI in NetRexx, JPython, Java and so on. You can compare this BeanShell to JPython and NetRexx by looking at past articles in this series (Vol. 5, issues 3 and 5, respectively).

Listing 3 shows the employee form that we prototyped in the interactive interpreter. Listing 4 shows the Java version of that prototype. If you compare the two, you'll notice they're very similar. Some notable differences are that the BeanShell version doesn't have a true class definition. Instead, it has some nested methods. Also, the BeanShell version of the "class" doesn't have a constructor or a main method. It took me about two minutes to convert the Java version to BeanShell. Since BeanShell is a subset of Java, the rest of the Rosetta Stone examples would be quite meaningless, that is, we already highlighted the major differences between BeanShell and Java.

DynamicJava and the Rosetta Stone Examples
Since DynamicJava is a fully functional interpreted version of Java, Rosetta Stone examples written in Java work in DynamicJava with few if any changes. In DynamicJava you define your classes just as you do in Java. Just like BeanShell, DynamicJava has an interactive interpreter. In addition, you can use loosely typed variables. DynamicJava is quite cool in its own right.

Rosetta Stone Adding BeanShell in Java
A good example of embedding BeanShell into a Java program is shown on the BeanShell Web site. The example is listed with some additional comments below:

import bsh.Interpreter; //Import the BeanShell Interpreter
...
Interpreter i = new Interpreter(); //Create a new instance of the interpreter.
i.setVariable("foo", 5); //Define a variable
i.eval("bar = foo*10"); //Evaluate an expression.
System.out.println("bar = "+i.getVariable("bar") ); //Get the value of a variable.

Scorecard
How does BeanShell score? Here's my opinion.

AUTHOR'S SCORECARD FOR BEANSHELL

  • Ease of use 10
  • Embeddability 10
  • Resemblance to parent language 7.5
  • Unique features 7.5
  • String parsing 0
  • Productivity 6
  • Working well with Java classes 9
  • Development environment/debugging 2
And here's my opinion of DynamicJava.

AUTHOR'S SCORECARD FOR DYNAMICJAVA

  • Ease of use 10
  • Embeddability 10
  • Resemblance to parent language 10
  • Unique features 5
  • String parsing 0
  • Productivity 5
  • Working well with Java classes 10
  • Development environment/debugging 2

14 of 15

Thus I give both scripting languages a score of 52 out of 80 based on the above criteria. Now remember, those criteria are based on a scripting-language philosophy of keeping things easy for the developer (see JDJ, Vol. 5, issue 2, for more information on the power of scripting languages). Drop by the JDJ Forum to grade BeanShell and DynamicJava.

Let's drill down on the above criteria a bit.

  • Ease of use: BeanShell was easy to install and easy to start using.
  • Embeddablity: BeanShell is easy to embed.
  • Resemblance to parent language: BeanShell strives to be a subset of Java with features added for scripting. However, the object scripting in place of Java classes is difficult at best, and quite different from Java. BeanShell seems to favor JavaScript's way of handling classes (although by no means is it identical to JavaScript). On the wish list for BeanShell is the ability to define classes using the Java style. If BeanShell did that, it would easily get a 10 in this category. I like the way DynamicJava defines classes.
  • Unique features: Neither BeanShell nor DynamicJava do well in this category. For example, the convenient way of handling bean properties saves one keystroke over the Java way of handling events.
  • String parsing: DynamicJava and BeanShell don't have any special string parsing abilities. However, in a future release BeanShell plans on adding regular expression capabilities into the language la Perl. If BeanShell did that it would easily get a 10 in this category.
  • Productivity: BeanShell and DynamicJava can access the complete Java APIs, which is an extensive class library. However, unlike Python, which has built-in language support for collection objects including collection literals that let you define a collection, iterate easily over Java collection and work with Bean properties as you do in TCL when creating an instance of a class, BeanShell and DynamicJava don't have any of the really convenient language features. Python and NetRexx language constructs make programming strikingly productive.
  • Working well with Java classes and APIs: You can instantiate Java classes, invoke Java methods and easily set up bean events in both, but you can't subclass Java classes and interfaces in BeanShell the way you can in DynamicJava, NetRexx and JPython.
  • Development environment/debugging: It's good to have an interactive interpreter, and BeanShell and DynamicJava have a good one. However, if you're used to having GUI builders, debugging in an IDE, setting watches and so on, forget about it. The development environment for these languages isn't up to par.
Parting Shots
Scripting languages are good for prototyping and rapid application development (refer to first article in series). Most Java developers don't want to learn new language syntax to get the advantage of scripting languages. DynamicJava and BeanShell fill a gap.

I think BeanShell has the advantage over DynamicJava in that its creator wants to see it evolve into a better scripting language. For example, he wants to add support for regular expression. On the other hand, the creator of DynamicJava just wants to be syntax compatible with Java as much as possible. I think that BeanShell and DynamicJava have a long way to go to get to the levels of mature scripting languages. DynamicJava won't add more features to make it easier on the programmer, that is, more scripting-like (see interview with creator of DynamicJava).

I think if BeanShell added the features that make JPython work so well with Java it would be much better. BeanShell syntax is more in tune with what people are used to (more so than NetRexx and JPython); it's Java-like. The JPython feature set is more in tune with what a scripting language should be. Combine them and throw in a few cool NetRexx features for good measure and you'd have one lean, mean, Java-like scripting language. NetRexx and JPython are mature scripting languages - more mature than BeanShell - but BeanShell has quite a niche (being more like Java).

Components need scripting languages. ActiveX has Visual Basic. JavaBeans has BeanShell.

Author Bio
Rick Hightower currently works at Buzzeo Corporation (www.buzzeo.com), maker of ZEOlogic, an EJB application server rules engine and workflow. He is a principal software engineer working on an EJB container implementation and distributed event management. In addition, he is author of a book, Programming the Java APIs with JPython, to be published by Addison Wesley. [email protected]

	

Listing 1: BeanShell Employee "class": 

Employee (){ 
String firstName, lastName; 
int id, dept; 
manager = null; 
__init(){ 
print("This far"); 
super.firstName = "John"; 
super.lastName = "Doe"; 
super.id = 1; 
super.manager=null; 
super.dept=1; 
} 
init(String fname, String lname, int id, manager, int dept){ 
super.firstName = fname; 
super.lastName = lname; 
super.id = id; 
super.manager = manager; 
super.dept = dept; 
} 
getManager(){ 
return this.manager; 
} 
String toString(){ 
StringBuffer buf = new StringBuffer(); 
buf.append(super.lastName+','); 
buf.append(super.firstName+','); 
buf.append(""+super.id); 
return buf.toString(); 
} 
__init(); 
return this; 
} 
print(Employee().toString()); 
joe = Employee(); joe.init("Joe", "Batista", 100, null, 1); 
ron = Employee(); ron.init("Ron", "Furgeson", 101, joe, 1); 
print(ron.toString()); 
print(ron.getManager().toString()); 
 
Listing 2: Java Employee class 

public class Employee{ 
private String firstName, lastName; 
private int id, dept; 
private Employee manager; 
public Employee(){ 
firstName = "John"; 
lastName = "Doe"; 
id = 1; 
manager=null; 
dept=1; 
} 
public Employee(String fname, String lname, int id, Employee 
manager, int dept){ 
firstName = fname; 
lastName = lname; 
this.id = id; 
this.manager = manager; 
this.dept = dept; 
} 
public Employee getManager(){ 
return manager; 
} 
public String toString(){ 
StringBuffer buf = new StringBuffer(); 
buf.append(lastName+','); 
buf.append(firstName+','); 
buf.append(""+id); 
return buf.toString(); 
} 
... 
... 
} 
 
Listing 3: BeanShell EmployeeForm: 

import javax.swing.*; 
import java.awt.GridBagLayout; 
import java.awt.GridBagConstraints; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import employee.Employee; 
EmployeeForm(){ 
JFrame frame; 
JTextField name; 
JTextField id; 
void init(){ 
super.frame = new JFrame("Employee Form"); 
pane = new JPanel(); 
super.frame.getContentPane().add(pane); 
pane.setLayout(new GridBagLayout()); 
// Create a name, and id text field. 
super.name = new JTextField(25); 
super.id = new JTextField(10); 
// Create and add a "Name" and "ID" label. 
JLabel nameLabel = new JLabel("Name"); 
nameLabel.setLabelFor(name); 
nameLabel.setDisplayedMnemonic('N'); 
GridBagConstraints constraint = new GridBagConstraints(); 
pane.add(nameLabel, constraint); 
JLabel idLabel = new JLabel("ID"); 
idLabel.setLabelFor(id); 
idLabel.setDisplayedMnemonic('I'); 
constraint.gridy=1; 
pane.add(idLabel, constraint); 
// Add the name and ID text field to the form. 
constraint.gridy=0; constraint.gridx=1; 
constraint.weightx=80.00; 
constraint.anchor=GridBagConstraints.WEST; 
pane.add(name, constraint); 
constraint.gridy=1; 
pane.add(id, constraint); 
// Create an okay button, add it, and set up its event handler. 
JButton okay = new JButton("Okay"); 
okay.setMnemonic('O'); 
constraint.gridx=1; constraint.gridy=2; 
constraint.anchor=GridBagConstraints.EAST; 
pane.add(okay, constraint); 
okay.addActionListener(this); 
frame.setVisible(true); 
frame.pack(); 
} 
void actionPerformed(ActionEvent event){ 
handleOkay(); 
} 
void handleOkay(){ 
String name, fname, lname; 
int index=0; 
int id =0; 
name = super.name.getText(); 
index = name.indexOf(" "); 
fname = name.substring(0, index); 
lname = name.substring(index+1, name.length()); 
id = Integer.parseInt(super.id.getText()); 
Employee employee = new Employee(fname, lname, id, null, 100); 
System.out.println(""+employee); 
} 
init(); 
return this; 
} 
ef = EmployeeForm(); 
 
Listing 4: Java EmployeeForm: 

import javax.swing.*; 
import java.awt.GridBagLayout; 
import java.awt.GridBagConstraints; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 
import employee.Employee; 
public class EmployeeForm extends JFrame{ 
private JTextField name; 
private JTextField id; 
public EmployeeForm(){ 
super("Employee Form"); 
JPanel pane = new JPanel(); 
getContentPane().add(pane); 
pane.setLayout(new GridBagLayout()); 
// Create a name, and id text field. 
name = new JTextField(25); 
id = new JTextField(10); 
// Create and add a "Name" and "ID" label. 
JLabel nameLabel = new JLabel("Name"); 
nameLabel.setLabelFor(name); 
nameLabel.setDisplayedMnemonic('N'); 
GridBagConstraints constraint = new GridBagConstraints(); 
pane.add(nameLabel, constraint); 
JLabel idLabel = new JLabel("ID"); 
idLabel.setLabelFor(id); 
idLabel.setDisplayedMnemonic('I'); 
constraint.gridy=1; 
pane.add(idLabel, constraint); 
// Add the name and ID text field to the form. 
constraint.gridy=0; constraint.gridx=1; 
constraint.weightx=80.00; 
constraint.anchor=GridBagConstraints.WEST; 
pane.add(name, constraint); 
constraint.gridy=1; 
pane.add(id, constraint); 
// Create an okay button, add it, and set up its event handler. 
JButton okay = new JButton("Okay"); 
okay.setMnemonic('O'); 
constraint.gridx=1; constraint.gridy=2; 
constraint.anchor=GridBagConstraints.EAST; 
pane.add(okay, constraint); 
okay.addActionListener(new ActionListener(){ 
public void actionPerformed(ActionEvent event){ 
handleOkay(); 
} 
}); 
this.setVisible(true); 
this.pack(); 
} 
public void handleOkay(){ 
String name, fname, lname; 
int index=0; 
int id =0; 
name = this.name.getText(); 
index = name.indexOf(" "); 
fname = name.substring(0, index); 
lname = name.substring(index+1, name.length()); 
id = Integer.parseInt(this.id.getText()); 
Employee employee = new Employee(fname, lname, id, null, 100); 
System.out.println(""+employee); 
} 
public static void main(String [] args){ 
new EmployeeForm(); 
} 
} 
  
 
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.