Thursday, March 20, 2008

Swinging: BGGA style.

So, to continue on with my playing w/ java closures, I now present Swing event handling: BGGA Style. Again, to compile this you will need the BGGA prototype. You can run it using your installed jre.

First, i'll show you the java version:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
* Created: Mar 19, 2008 5:48:43 PM
*
* @author Robert O'Connor
*/
public class UsualJavaGui {
JFrame frame = new JFrame("Usual Java Example");
JButton button = new JButton("Press me");

public UsualJavaGui() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
frame.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UsualJavaGui();
}
});

}
}

I think you get the gist of what it does. Now the BGGA version.

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;

/**
* Created: Mar 19, 2008 7:35:15 PM
*
* @author Robert O'Connor
*/
public class BGGAGui {
JFrame frame = new JFrame("BGGA Frame");
JButton button = new JButton("Press me");

public BGGAGui() {
button.addActionListener({ActionEvent evt => System.out.println("Button pressed");});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
// thanks to neil gafter!
SwingUtilities.invokeLater({ => new BGGAGui(); });

}
}

What occurs within the the addActionListener() is that when you click the button, that closure is invoked; it does the same thing the java one does (print "Button pressed" to the screen). I'm not sure how to write the invokeLater() method using BGGA to reduce its verbosity. If anybody knows, could you tell me? When the code is executed; the closure is executed and a frame is displayed; yadda yadda.

1 comment:

Neal Gafter said...

SwingUtilities.invokeLater({ => new BGGAGui(); });