Friday, April 24, 2009

Monday May 18: JN25, part four

Before beginning work on your game projects, I am going to have you each make another addition to the program I have been demonstrating to recently. It will be useful for the following reasons:


1) It will set up for the beginning of next wek, when we can have some $#+33^ 6((3 fun with this program



2) it will demonstrate how you can use arrays and loops to create large numbers of similiar components


3) It will show some fun stuff you can do with swing type labels


OK, here we go again


A) In the "declarations" section of this program, you will add two new JPanels, two JLabels and twoArrays, like so:

JPanel alpha,omega;
JLabel noCode, crypto;

//use with clear JTextArea & noCode JLabels
String[] qwerty ={"q","w","e","r","t", "y", "u", "i","o","p","a","s","d","f","g","h","j","k","l"," ","z","x","c","v","b","n","m", ".", ",","!"};


//use with enc JTextArea & crypto JLabels
String[] coded ={"!","@","#","$","%", "^", "&", "*","(",")","+","=","{","}","[","]","1","2","3"," ","4","5","6","7","8","9","0", ".", ",","!"};



You will notice that each array has thirty elements and that both are String arrays. If you believe that they can be used together for a simple cypher, you guessed correctly

Compile and run now to make sure you have no errors before we proceed


B) Just above the end of the constructor line that makes the program visible, add this method call:
addAlpha(); //call method set up clear keys


C) create this new method just below the (STILL!) empty actionPerformed method block:

//method to populate JLabels for clear keys
public void addAlpha()
{
alpha = new JPanel();
alpha.setBounds(20,150,300,200);
alpha.setLayout(new GridLayout(3,10));
for (int i = 0; i <
{
noCode = new JLabel(qwerty[i],SwingConstants.CENTER); //create a label noCode.setBorder(new LineBorder(Color.blue, 3)); //give it a blue border
alpha.add(noCode); //add label to Panel
System.out.println(qwerty[i]);
}
//end for loop fill clear labels
Ultra.add(alpha); //add panel to container
}//end addAlpha




OK, that's great, but what does it all mean? Well, let's break it down:

1) You're making a new JPanel, with a GridLayout of three rows of ten


2) You're using a for loop that will run the "length" of the qwerty Array


3) each pass through the for loop creates a new JLabel that has the text found at the position in the qwerty Array that is the same as the value of "i".


4) So if is 4, then you go to position 4 in the array, which is the letter "t", and thats what gets put in that label


5) each JLabel gets a pretty blue border whose thickness is set to 3


6) the value of the label text gets outputted to the system console


7) when the loop is done and the JPanel is filled, put the JPanel into the container


30 labels in an eyeblink!


Cheers,
Mr. L




No comments:

Post a Comment