Experimenting with Scraps of Code
When experimenting with code in Eclipse it is sometime easier to use
the “scrapbook” feature which
doesn’t require defining complete java classes - perfect for writing
snippets of spike code. For instance,
you might create a new scrapbook page within your project to explore
Maps and Iterators.
String key[] = {"one","two",
"three" };
int data[] = { 1, 2, 3 };
System.out.println("key/data pairs");
Map m = new HashMap();
for (int i=0; i<key.length; i++) {
System.out.println("#"+i+": "+key[i]+", "+data[i]);
//place into a map - data must be an object type
m.put(key[i], new Integer(data[i]));
}
//Iterate over the map retrieving data for all its keys.
for (Iterator i=m.keySet().iterator(); i.hasNext(); ) {
String aKey = (String) i.next();
Integer anInt = (Integer) m.get(aKey);
System.out.println("Saved Key = "+ aKey + ", "+
anInt);
}
To enter the code, select New -->
Java --> Java Run/Debug --> Scrapbook page. Then put
the source code in to the scrapbook page. To get to actually run
correctly, you will need to tell
Eclipse to import the java.util.*
package. Use the right menu--> Set
Imports ... option.
To execute, select the lines of code to run, then do right-menu --> Execute.
Remember the code from a spike is not considered production code. It is
a way to explore how
something might be implemented; it is useful in helping to assess the
effort and risk involved. Several
spikes may be necessary before understanding enough to begin production
development. This is
especially true if the developers are implementing software unlike
their previous experience. A balance
must be struck between spending too much “up front” time planning and
learning and coding without
sufficient knowledge. Agile techniques spend less up front time but
must compensate by adjusting the
design continuously (refactoring).
You can even define new classes and test out GUI components in the
scrapbook. Of course,
you may need to add additional imports (java.swing, java.awt)
class GraphicButton extends
JButton {
public void
paintComponent(Graphics g) {
//super.paintComponent(g); // can't refer to super in scrapbook
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.RED);
g2.fillRoundRect(10, 10, getWidth()-20,
getHeight()-20, 14, 14);
g2.setPaint(Color.BLACK);
g2.drawRoundRect(10, 10, getWidth()-20,
getHeight()-20, 14, 14);
g2.drawString("Graphic Test", 40, 40);
}
public
Dimension getPreferredSize() {
return new Dimension(200,100);
}
}
JFrame frame = new JFrame("JButton
Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont =
frame.getContentPane();
JButton hello = new
GraphicButton();
cont.add(hello);
frame.pack();
frame.setVisible(true);
Back
to 435 weekly