Tuesday, April 27, 2010

Reverse a String in Java

Code for reversing a string in Java.

public static String reverse (String s) {
int length = s.length();
int last = length - 1;
char[] chars = s.toCharArray();
for (int i=0; i < length/2; i++){
char c = chars[i];
chars[i] = chars[last - i];
chars[last] = c;
}
return new String(chars);
}

Tuesday, April 13, 2010

Using CardLayout in Netbeans

I've created this tutorial because of the trouble I had with using the CardLayout in Netbeans. It's a fairly useful tool for any GUI design and should be known by any GUI programmer.

First create a new project like you normally would.



Next add a JFrame. Then add a next button and name it as you like. Now add a JPanel to this JFrame, this JPanel is what you'll be using for your Card Layout. I suggest naming it mainJPanel



Add three new JPanels to your already existing JPanel, then set the layout to Card Layout as I did in the screen.



Add labels to each of the JPanels so you can distinguish them from each other.

Then add an action listener to the next button and add this code

CardLayout cl = (CardLayout)mainJPanel.getLayout();
cl.next(mainJPanel);


The next command is where it does the work, Netbeans adds all three panels to the mainJPanel, but the programmer needs to create the CardLayout object.

This tutorial was created using Netbeans v 6.7.1