Friday, March 21, 2008

Swing first class w/ FCM.

I got to play with the First-Class methods (FCM) prototype; it's pretty cool. So here we go: Java version then FCM version.

To run the FCM version: compile it using the prototype; then simply type: java FCMGui and you're set. If you need help feel free to e-mail me.


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();
}
});

}
}

Standard java Swing GUI with a frame and a button; press it a message appears in your console. Now, FCM version:


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

/**
* Created: Mar 21, 2008 6:55:52 PM
*
* @author Robert O'Connor
*/
public class FCMGui {
JFrame frame = new JFrame("FCM Example");
JButton button = new JButton("Press Me");

public FCMGui() {
button.addActionListener(#(ActionEvent evt) {
System.out.println("Button pressed");
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(# { new FCMGui();
});

}
}

Same thing: But what the hell is going on? First off, what we declared is called an anonymous inner method; if you remember, it's a First-Class method meaning that it exists in itself. Currently in java, a method must be enclosed in a class, and cannot be referred to on a first-class level.

No comments: