Friday, April 24, 2009

Monday May 18: JN25, part five

Allllrighty then, this is the very last part of the little program I've been showing you. This is the part that starts really bringing it together




Here's what to do:





A) first off, we add a KeyListener along with all those other listeners at the top of the program, like so (MAKE IT LOOK LIKE THIS, DO NOT ADD ANOTHER WHOLE LINE):

implements ActionListener, ChangeListener, ItemListener, KeyListener




B) If this key listener thing sounds familar, well it should: your classmate Evan taught this to you weeks ago




C) The KeyListener requires that three methods be declared, even if you only are goiong to use one of them. Hey, I didn't set it up that way...not my idea! Anyway, just add this block underneath the (STILL empty) actionperformed code block




public void keyTyped(KeyEvent e) { }//empty method
public void keyPressed(KeyEvent e)



{





}// we will use this method


public void keyReleased(KeyEvent e) { }//empty method




D) Now the next step will use a switch case, which is similar to an if statement, but is especially adept at using ints. Here's the first small part which we will setup INSIDE the curly braces for the keyPressed(KeyEvent e) method



switch (e.getKeyCode()) //every key has an integer keyCode
{



case KeyEvent.VK_Q: // 1st in array?


whichOne=0;


break;


case KeyEvent.VK_W: // 2nd in array?


whichOne=1;


break;


case KeyEvent.VK_E: // 3rd in array?


whichOne=2;


break;


case KeyEvent.VK_R: // 4th in array?


whichOne=3;


} //end switch case


System.out.println(whichOne); //show value of integer in console
String codedStuff = enc.getText(); //get the stuff already in code JTextArea enc.setText(codedStuff + coded[whichOne]);//add new stuff into code JTextArea
} //end keypressed






E) The quick ones among you will have already figured out that this method receives input in the form of a key that's been pressed, then uses that key to set the value of an integer. This intger then points to an element in the coded Array, and then types that String to the other JTextArea, appending it at the end of encrypted text thats already there.




The entirety of the switch case can be found here:

http://www.box.net/shared/ppxd8c35tz




cheers,

Mr. L

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




Wednesday April 29th: JN25, part three

Today we will keep this part of the class to a minimum: you will only need to add a JComboBox to the JPanel from yesterday, you know, the one with the slider in it. You will then use this JComboBox to determine the font of the text in the JTextArea. Here's how you do it:

A) Add a new "listener" at the end of the line that says "implements ActionListener, ChangeListener"
so that it reads implements ActionListener, ChangeListener, ItemListener

we need an itemlistener here because comboboxes are basically lists of items, in this case, font names

B) In the constructor, add the code for creating the JComboBox and its JLabel JUST BELOW WHERE YOU ADDED THE SLIDER AND ITS LABEL

Here is the code you add:
//add array elements to JComboBox
daFonts = new JComboBox(typeStyle);
daFonts.setSize(150,25);
//add itemlistener to combobox
daFonts.addItemListener(this);


setWordz.add(daFonts); //add combobox to panel
whatDaFont = new JLabel("Please Choose a Font",SwingConstants.CENTER);


whatDaFont.setSize(150,25);

setWordz.add(whatDaFont); //add JLabel for combobox to panel


C) As you might imagine, you have to add a new ItemListener method to handle the event of you choosing a new font from the list. Here it is, and please enter it just below the other one you made yesterday:

public void itemStateChanged(ItemEvent e)

{
//set String variable for font style to item chosen in combobox
whichFont = daFonts.getSelectedItem().toString();


ChangeDemWordz(); //call method set size and font of JTextAreas
}//end itemStateChanged


As you can see, you're setting a String variable equal to whatever has been chosen from the JComboBox, then calling the same method from yesterday to apply it to text that gets typed

See how easy?
Mr. L

Tuesday April 28th: JN25, part two

OK, so yesterday, part of what you did involved working on a small program that I have introduced. Today, before you work further on your game programs, I am going to demonstrate to you some added functionality of this other program, using a component we're already familiar with -- the JComboBox -- and one we haven't worked with yet, the JSlider.


We are going to use these two components to chnage the font style and size of the text typed into the JTextAreas. Here we go!


A) first off, you need to add this code block to your "declarations", I would do it just below the line that runs "JPanel alpha,omega, setWordz;"


//use to fill JComboBox

String[] typeStyle ={"Impact ","Arial", "Comic Sans MS"};

JComboBox daFonts;

String whichFont= typeStyle[0]; //start with first font in Array

JSlider daSizes;

int fontBigness=25; //start at font size 25

//use to provide info about JSlider for font sizes and JComboBox font styles

JLabel whatDaFont, wowSoBig;

As you can see, there are actually FOUR components we will be using eventually, but two of them are JLabels. These JLabels will just have some text in them to describe the function of the component they sit next to


Also, we will use a String to describe which font is going to be used by picking it from a String Array full of font names. Additionally, there is an int to desribe how big the font size is


B) NEXT, you need to add the following to your constructor:


//add in Panel with JSlider and JComboBox here
setWordz = new JPanel();
//new JPanelsetWordz.setBounds(250,380,300,50);
setWordz.setLayout(new GridLayout(2,2));
daSizes = new JSlider(); //new JSlider
daSizes.setValue(fontBigness); //start at default font size
daSizes.setSize(150,25);

setWordz.add(daSizes); //add slider to panel
wowSoBig = new JLabel("Slider Sets Font Size",SwingConstants.CENTER);

wowSoBig.setSize(150,25);

setWordz.add(wowSoBig); //add JLabel for slider to panel


As you can see, this sets up a JPanel that has a gridlayout with four sections. Today, you will just be filling two.


The first thing we put in the Panel was a "JSlider". It's a little control that can be slid back and forth. By default, it starts at a value of 50 out of 100, but that can be set to something else. In this case, we set it to the value of an integer that starts at 25


The other thing was a JLabel. This just gives you some info about what the JSlider will do. You will notice that I've shown the way to center the text in the JLabel


C) OK, if you compile and run the program now, you can move the slider thingy around, but it does nothing. Here's what we do to rememdy that:


D) First off, you have to add a new kind of Listener way up at the top of the program, after the part that says "implement ActionListener". make it read like so:

implement ActionListener, ChangeListener


The next obvious step is to add a ChangeListener to your slider, like so:

daSizes.addChangeListener(this);//add changelistener to slider


E) Once you have a ChangeListener on the JSlider, you gotta tell it to DO something once you have its attention. So, just below the (still empty) actionPerformed method block, add in this new method block:


public void stateChanged(ChangeEvent ce)

{

fontBigness = daSizes.getValue();

System.out.println(fontBigness);

ChangeDemWordz();//call method to change the font size & face

}


All this method does is to to change the integer "fontBigness" to the value of the JSlider as you move it around...you can see it change in the system console. BUT, it doesn't actually change the size of the font in the JTextAreas, which is why you call another method, a "homegrown" method called :


public void ChangeDemWordz()
{

clear.setFont(new Font(whichFont, 0, fontBigness));

enc.setFont(new Font(whichFont, 0, fontBigness));

}//end method ChangeDemWordz()


OK, so re-compile and run the program. You should be able to change the font size of text in this program at will.


Once you're done with that, proceed to working on your game programs


Cheers,

Mr. L

Tuesday May 12th: JN25, part one

There is a program I am going to have you build over the next few days which has some interesting features which I must demonstrate to you while you work on your game programs. Here we go....


There is a file called "JN25" which you will need to download from a folder found here:

http://www.box.net/shared/aha47pf4fi



When you compile and run it, you will find a very simple program which actually doesn't have much in it just yet. There are only two simple things we are going to do with this program:


A) add two JTextAreas inside two JScrollPanes which have vertical scrollbars, just like those we put the JEditorPanes inside a few weeks back


B) add a small correction to a slight problem you will no doubt notice almost immediately


For part A, we need to construct two JTextAreas that are next to each other. Here's how the first one gets built:


in the programs constructor, just below where it states that the JFrame's container has a "null" layout, enter in this code block:


clear = new JTextArea("", 20,20);
clear.setBounds(10,10,400,100);
clearScroll = new JScrollPane(clear);
clearScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

clearScroll.setBounds(10,10,400,100);
Ultra.add(clearScroll);



This adds a new JTextArea, which unlike a TextField, has multiple rows as well as many columns: how many has been determined by the 20,20 ints above


The JTextArea is added inside a scrollpane, because if you end with lots of text in it, you might need to scroll up and down to read it all


The ScrollPane is then added to the container, and since that container's layout is set to null, you need to setBounds on the ScrollPane to determine where it gets placed.


Once you have that set up, all you need to do to put the other JTextArea/scrollpane onto the program is to copy and paste the code block from above, paste it right below that first code block in your program, then change the neame of the JTextArea from "clear" to "enc" and the name of the JScrollPane from "clearScroll" to "encScroll".


And of course, you have to change WHERE the second textarea/scroller is placed. Hint: if you set the first int valuein "setBounds" to something bigger than "10", say "450", that should do it



OK, one last thing: when you type in either of these JTextAreas, you will notice that they don't "word wrap" Even though the JScollPane has a vertical scrollbar. !!!!#!@##!~!!!!!!!


fear not though: you can control that by adding these three lines just below where you setbounds for the first JTextArea:

clear.setEditable(true);
clear.setLineWrap(true);
clear.setWrapStyleWord(true);


Make sure to do it for the other JTextArea as well. When you're done, your groups may proceed onwards with your game projects



Cheers,
Mr. L

Monday April 27th: Before we begin, a simple poll

Greetings, and welcome back


Before we begin, I would like for you to meet as teams and decide how much additional time you will require to work on your game projects. We can either limit it to the rest of this week, or extend it to include both this week and next week. So, it either ends May 1 or May 8.


Decide by teams and then make one group discussion post per team. The subject line should include all the names of the people working together as a group, followed by either the May 1 or the May 8 deadline.

Additionally, each team should indicate if they feel the need to have the entirety of today's class devotd to their project or not. I have several techniques that I would love to demonstrate, but they can wait if you need the additonal time

Lastly, in the body of your post, please indicate whether or not your team feels sufficiently confident of your program to be able to present it to the rest of the class, field questions, ect etc.


Once that is done, we can go on to the next step



Cheers,
Mr. L



































an "E"

Wednesday, April 15, 2009

wednesday April 15th: prepping for beyond the break

greetings, Java-nated ones,

as you may have guessed, I am not in today. That being the case, I have decided to go forward with two items I meant to work on after the break, to wit:

A) Anything that you have missed passing in, either as an attached Java assignment or as a group discussion posting, start getting that made up today. If you forget what you owe, just compare recent blog posts that I have made to group discussion posts you were supposed to have made

B) Begin setting up a list of basic (no, I can't hear you from here) ideas for developing some sort of game program in Java, using knowledge which already have and employing both AWT and Swing components as needed. I'm not necessarily talking about WoW or Halo -- obviously-- but something a little more doable. When I return, I'll demonstrate something along those lines. Here are some things you should consider for your game:

1) What is the object of the game?

2) does it have identifiable characters?

3) does it have multiple skill levels?

4) how does it register input?

5) can it have more than one player?

6) how does it keep score?

7) how do you determine when the game ends?

8) can you save games? high scores? levels

9) can you "build" a character? -- (that'd be a bit more difficult, but perhaps fun to try)

Please think about these issues, then create a Group discussion post named after yourself, plus the phrase "Java gaming". Describe what you have in mind for your game.

And yes, in answer to your question, you may work with partners on this if you wish. Please include that in your posts...but remember, ALL of you must make that first post.

Mr. L

Saturday, April 11, 2009

Monday April 13th: Improving our "browser"

Gentlemen,

If you will recall, last week, before Evan made some noise with you and I showed you a little bit about JToolbars, we wer working on a kind of "browser": not exactly Firefox, but it was a start. I had told you that at some point, I would show you how to modify this program so that Favorites you added would STAY in your favorites list, by using some basic File reading and writing capabilities.

Before I go any further, I want to point out from the beginning that there are some obvious "bugs" in the way this program is setup. My purpose in doing this is to get you to think about how YOU would fix the errors, as well as being able to look for them in the first place. If you don't know there's a problem, it's kind of like that giant squid in the Family Guy episode: it's there, whether you acknowledge it or not.



Also, there's a file that I used in this version of the program which you can download here:

http://www.box.net/shared/n32n5qk2qs

It's called "addys.pml". Later on, you can modify this file, but for now, you can just use it as we progress through this lesson.

so OK, here we go:

The improvement to be made today involves being able to REALLY save favorites to a list. In the most recent incarnation of this program, you were able to use an "Add to Faves" button to add a particular website address to your JComboBox; but when the program closed, all those newly added Favorites were lost.

The solution is to use some elemental File writing and reading capabilities to your program. If your favorites list is built by reading from a separate text file, then it follows that anything you WRITE to that file during the course of running the program should be available the next time you run it. Here's what I did:

In your constructor, you should have a code block that looks like this:
webURL = new Vector();
webURL.addElement("
http://www.google.com");
webURL.addElement("
http://www.thinkgeek.com");
webURL.addElement("
http://www.yahoo.com");
webURL.addElement("
http://www.foxnews.com");
You need to comment out that entire block!
Well now, if you do that, your Favorites list will be empty. So, we've gotta find some other way of populating it. Here's what I did:

Just below the stuff I commented, I made a method call:
readFilesMakeFaves(); //call this method

This means I have to create the method that will be called; just make sure you don't embed this thing inside another method. That would be bad. Here is what my method looks like:

private void readFilesMakeFaves( )
{
webURL = new Vector();//create vector
//add to that vector using file read
try {
BufferedReader in = new BufferedReader(new FileReader("addys.pml"));
String str;
while ((str = in.readLine()) != null)
{
System.out.println(str); //show whats going into file in system console
webURL.addElement(str); //add to the vector the line just read
}
in.close( ); //stop reading
}
catch (IOException e)
{System.out.println("file not found or is null"); }
}//end readfilemakefaves method

So what this filereader does is to open up the file called "addys.pml", and read it one line at a time. As it does so, it adds each line to the JComboBox. It also prints out each line to the System console. So far, so good!

The next step is to modify the "Add Faves" button so that it can add a favorite as a line into the "addys.pml" file. This will mean that even if you close the program and then re-start it, the new favorites places that has been added will STILL be in the list, which is an improvement over the previous system. Here is how I did it:

private void addFaves()
{
//read into the addy.pml file the address in JTextField
try {
//open a writer to append to end of addys.pml file which stores faves
BufferedWriter out = new BufferedWriter(new FileWriter("addys.pml", true));
out.newLine(); //drop to next line
out.write(WhereTo.getText()); //write in contents of JTextField
out.close(); //stop writing fer cryin' out loud
}
catch (IOException e) { }


OK, here's what I want you to do after you've saved, compiled and run this thing:

A) At some point, I will want you to add a JToolbar to this program which will have graphical buttons that provide another way of doing the stuff we've already been doing with this programB) There's at least one glaring omission with this program, something it should do but doesn't. Figure out what it is, then figure out YOUR way to fix it.

C) After you've done both A and B above, please make a discussion post describing the problem you found and your solution.

D) Please email your completed program before the end of the class.

Cheers,
Uncle Paulie

Thursday, April 9, 2009

Thursday, April 9: Evan's at bat and here's the rest of the code!

public boolean keyDown(Event e, int key)

//this boolean called keydown sets the key so if it is pushed, the sound will play.

{
if(key=='q'key=='Q')
{

if (lowCPlaying == false)
{
lowC.loop();
}
lowCPlaying = true;
}


if(key=='w'key=='W')

{

if (lowDPlaying == false)

{

lowD.loop();

}

lowDPlaying = true;

}



if(key=='e'key=='E')
{

if (lowEPlaying == false)

{

lowE.loop();

}

lowEPlaying = true;

}
if(key=='r'key=='R')

{

if (lowFPlaying == false)

{

lowF.loop();

}

lowFPlaying = true;

}
if(key=='t'key=='T')

{

if (lowGPlaying == false)

{

lowG.loop();

}

lowGPlaying = true;

}
if(key=='y'key=='Y')

{

if (lowAPlaying == false)

{

lowA.loop();

}

lowAPlaying = true;

}

if(key=='u'key=='U')

{

if (lowBPlaying == false)

{

lowB.loop();

}

lowBPlaying = true;

}

if(key=='i'key=='I')

{

if (midCPlaying == false)

{

midC.loop();

}

midCPlaying = true;

}

if(key=='o'key=='O')

{

if (midDPlaying == false)

{

midD.loop();

}

midDPlaying = true;

}

if(key=='p'key=='P')

{

if (midEPlaying == false)

{

midE.loop();

}

midEPlaying = true;

}

if(key=='a'key=='A')

{

if (midFPlaying == false)

{

midF.loop();

}

midFPlaying = true;

}

if(key=='s'key=='S')

{

if (midGPlaying == false)

{

midG.loop();

}

midGPlaying = true;

}

if(key=='d'key=='D')

{

if (midAPlaying == false)

{

midA.loop();

}

midAPlaying = true;

}

if(key=='f'key=='F')

{

if (midBPlaying == false)

{

midB.loop();

}

midCPlaying = true;

}

if(key=='g'key=='G')

{

if (highCPlaying == false)

{

highC.loop();

}

highCPlaying = true;

}

return true;

}//end keyDown method









public boolean keyUp (Event e, int key)

//this makes a boolean so when the key is not being pushed the sound will stop.

{

if(key=='q'key=='Q')

{

lowC.stop();

lowCPlaying = false;

}if(key=='w'key=='W')



{

lowD.stop();

lowDPlaying = false;

}


if(key=='e'key=='E')

{

lowE.stop();

lowEPlaying = false;

}if(key=='r'key=='R')

{

lowF.stop();

lowFPlaying = false;

}if(key=='t'key=='T')

{

lowG.stop();

lowGPlaying = false;

}if(key=='y'key=='Y')

{

lowA.stop();

lowAPlaying = false;

}if(key=='u'key=='U')

{

lowB.stop();

lowBPlaying = false;

}

if(key=='i'key=='I')

{

midC.stop();

midCPlaying = false;

}

if(key=='o'key=='O')

{

midD.stop();

midDPlaying = false;

}

if(key=='p'key=='P')

{

midE.stop();

midEPlaying = false;

}

if(key=='a'key=='A')

{

midF.stop();

midFPlaying = false;

}if(key=='s'key=='S')

{

midG.stop();

midGPlaying = false;

}

if(key=='d'key=='D')

{

midA.stop();

midAPlaying = false;

}

if(key=='f'key=='F')

{

midB.stop();

midBPlaying = false;

}

if(key=='g'key=='G')

{

highC.stop();

highCPlaying = false;

}


return true;

} // end keyUp method

Wednesday, April 8, 2009

Thursday, April 9: Evan's at bat -- and man is he LOUD!

[Note from Mr. L: today we will be having the second in our series of student led programming classes. If you care to be the next volunteer, you know where to find me]





hello grand privateers - this is your BloodSail Admiral, Abquhazar!
Today we will be looking at a simple sound player. I attempted to make this in Visual Basic but I Epic failed.... and yet somehow, I got it in JAVA!




but any ways, we are going to learn how to play the violin today =D


lets break this down shall we?
we are gonna start this with the usual... please download the initial file at


http://www.box.net/shared/nf2gty9c0i





It has the startup file with three empty methods: init, keyDown and keyUp

The file is meant to be played as an Applet, btw.




now lets declare some things; we will do that just ABOVE the init( ) method:

AudioClip lowC, lowD, lowE, lowF, lowG, lowA, lowB, midC, midD, midE, midF, midG, midA, midB, highC; //all this stuff should go on one line!




int keyPressed;


I made enough sound files to play 2 octaves in C Major. Personally, C Major is my favorite scale but if you're not into music theory its all the same.


now we declare some booleans....you know, things that are either true or false. In this case, we wanna know if a particular note is playing....

boolean lowCPlaying,lowDPlaying,lowEPlaying,lowFPlaying, lowGPlaying, lowAPlaying, lowBPlaying, midCPlaying,midDPlaying, midEPlaying, midFPlaying,midGPlaying, midAPlaying, midBPlaying, highCPlaying;
//all this should should go on one line!!!



Once again, Iused 2 octaves of notes in a moajor scale.... thats 16 notes right there.




ok, so now get into our public void - once again, we have many sound files to load so lets get crackin'.


Fill this empty init method so that it looks like this:
public void init( )

{


try


{


lowC=getAudioClip(getCodeBase(),"lowc.mid");


lowD=getAudioClip(getCodeBase(),"lowd.mid");


lowE=getAudioClip(getCodeBase(),"lowE.mid");


lowF=getAudioClip(getCodeBase(),"lowF.mid");


lowG=getAudioClip(getCodeBase(),"lowG.mid");


lowA=getAudioClip(getCodeBase(),"lowA.mid");


lowB=getAudioClip(getCodeBase(),"lowB.mid");


midC=getAudioClip(getCodeBase(),"midC.mid");


midD=getAudioClip(getCodeBase(),"midD.mid");


midE=getAudioClip(getCodeBase(),"midE.mid");


midF=getAudioClip(getCodeBase(),"midF.mid");


midG=getAudioClip(getCodeBase(),"midG.mid");


midA=getAudioClip(getCodeBase(),"midA.mid");


midB=getAudioClip(getCodeBase(),"midB.mid");


highC=getAudioClip(getCodeBase(),"highC.mid");


}//end try



catch (Exception e){ } //end empty catch

} //end init





You have to use a "try catch" to init the sounds for the same reason you use it when loading a webpage: you have to have a "just in case' event in case the sounds aren't there.




So now after all the sounds are loaded, we will set up keydown commands to play the sound! We will put this in the boolean called "keyDown". Here we go...




INSIDE the public boolean keyDown method, just above the "return true" statement, add this:



if(key=='q'key=='Q')


{


if (lowCPlaying == false)


{


lowC.loop();


}


lowCPlaying = true;





This is just one sound. lets see if you can figue some of this out - I'll put the next post up in a few minutes to show the rest...






now as we might realize, there is no way to stop the sound once is has played... SO we are gonna have to make another boolean called keyUp. now im not going to tell you how to fix this problem just yet... lets have your brain go for a little jog...





































any one get it? Well here is the spoiler for all the n0obs who didnt try....

Put this in the keyUp method, just above the "return true"





if(key=='q'key=='Q')


{


lowC.stop();


lowCPlaying = false;


}





Save, compile, then run the program...when you do, you should be able to play a low C when you press the "Q" key.





The rest of the program is about adding in more if statements to both the keyUp and keyDown methods: other sounds connected with other keys. See if you can figure that out on your own....if not, then I'll give ya the complete set in another blog post

Tuesday, April 7, 2009

Wednesday, April 8: Tooltips and rollovers and Togglers, O my!

OK, now for the second phase of today's adventure: tooltips! This is actually pretty simple to do: to the first JButton you made, add this line of code:

Smile.setToolTipText("Always look on the bright side of life!");



then re-compile and run the program. You should get a message that pops up each time you leave the mouse over any particular JButton.



Speaking of rollovers, if you add this line of code:

Utool.setRollover(true);

after this liner of code

Utool.setFloatable(true);



you will get another effect showing which JButton you are about to select





OK, now for our other component, the JToggleButton. This component acts like a kind of light switch: it has an on and off position, and you can make things happen in your program based on that. It can be added to your JToolbar like any other JButton, and it can make use of another type of Listener, an "ItemListener" (This type of listener can also be used by radio buttons, but we'll get to that some other time) So, first things first, lets add an ItemListener to your program:

add this , ItemListener
after this implements ActionListener
put 'em both on the same line


then, declare this:
JToggleButton JTB;


and then add it into memory like so
JTB = new JToggleButton(new ImageIcon("gearHead.jpg") );
JTB.setToolTipText("Gear Up, Mates!");
JTB.addItemListener(this);
Utool.add(JTB);




Finally, you need to add an ItemStateChanged method to your program. You can probably do this just below your actionPerformed method, that's where I did it:


public void itemStateChanged(ItemEvent evt)
{
if (evt.getStateChange() == ItemEvent.SELECTED)
{
Utool.setFloatable(false);
}
else
{
Utool.setFloatable(true);
}
}//end itemStateChanged




Cheers,

Uncle Paulie

Wednesday, April 8: and now for something completely different...

greetings, one and all!



Today, we will be learning about a couple of really neat components that can make your programs that much more legit acting and looking. The first one is a JToolbar, and it is exactly like it sounds: it functions in much the same way as the toolbar you find in the browser you're using right this second. The second is a JToggleButton, which can be used to turn things on and off.



When we're done playing with these two new additions, you will need to do the usual routine of applying what you've learned to something else you already knew, AND sending your new program by email, AND posting a discussion about it. Plus, after you're done with that, you will get to apply what you've learned to something that we haven't covered in class, which I know many of you are doing already anyhow. Btw, if there is still some interest by any of you in leading the class on a particular topic of your choosing, please let me know.



OK, lets get going: download the Java file and the image files found here:

http://www.box.net/shared/zkrrerzdfx



and put 'em all in a separate directory inside your main Java folder



The first step to take after opeing this program in TextPad is to add a JToolbar to it. Add this to your declarations:

JToolBar Utool;


and then add it to memory in your constructor like so:

Utool = new JToolBar("Standard ToolBar, Inc.",JToolBar.HORIZONTAL );
Utool.setFloatable(true);




and then add this line:

ToolBox.add(Utool);



just above this line:
Hammer.setVisible(true);



this gets you a toolbar that starts horizontal and can be dragged around (more on that later)

BUT, if you compile and run your program now, you won't see very much: you have to put some JButtons on this thing first! So add this to your declarations:

JButton Smile, Stop, BraveHeart;



and then add this first JButton to your JToolbar, like so:

Smile = new JButton(new ImageIcon("mrHappy.jpg") );
Smile.addActionListener(this);
Utool.add(Smile);




Save, compile, then run your program. What you should have now is a MUCH more visible JToolbar which has one button in it. AND, you can drag that JToolbar around all over the place. Pretty neat, huh?



Now, add those other two JButtons to your Jtoolbar, then lets get to the next phase



Cheers,

Uncle Paulie

Sunday, April 5, 2009

Monday April 6 : additional stuff for our Swing Browser

Greetings JavaNoidz!



Today is going to be a simple two step process:



A) I will show you something pretty simple to do, that can be applied to ANY program you create here, that's pretty cool, AND its a response to a request that several of you had made.

Sometimes, you just gotta give the people what they want...



B) After that, you will have the rest of the class to further develop this mini browser we've been working on. Add to it something that we've worked with before, perhaps a menu or the ability to make use of saved files to extend its capabilities.



Remember, BEFORE the class ends, email me your completed program with its new powers, AND make a post on our Google group titled "what MY browser can do"





OK, so here's something easy and cool to do that will work with any program:



0) open the folder where your mini browser is stored



1) start up TextPad, and open your mini browser program



2) start up a new document, and type the following:



start javaw CreateTabbedPane



where "CreateTabbedPane" is the name of the class file you wish to run.
DO NOT add the ".class" extension




3) save this new file as StartBrowser.bat INSIDE THE SAME FOLDER AS YOUR PROGRAM. make SURE you add that ".bat" extension



4) This will make a batch file inside your folder that you can click on. Doing so will start your minibrowser program WITHOUT the annoying, telltale "command prompt" window --> that's why you use "javaw" to invoke your program



5) But wait there's more! It's not sold in any store! If you create a shortcut to this batch file, you should be able to drag that shortcut anywhere, even onto your Start button, which will make it part of the Start menu



6) But wait, there's STILL more ! If you right click on your new shortcut, and then click on "Properties", you can go to the "shortcut" tab, then click on the "Change Icon" button. This allows you to browse for an icon that looks cooler than the little gear thingy looking device you're using now



7) But wait: if you call RIGHT NOW, you can go to this address:

http://www.iconarchive.com/



and download any kind of icon file you want. Just download them to your folder, and then when you change the icon, just browse top your folder, and choose the icon you like :-)



Cheers,

Uncle Paulie

Thursday, April 2, 2009

Friday April 3: Java Swing Tabbed Browsing part Six

Alrighty then, for our last trick together before you surge ahead on your own, why don't we make an "Add to Favorites" type component? This would be something that would allow you to add additional addresses to your ComboBox. Here's what I did:

A) I declared a new button:
JButton Bravo;

B) created it in memory and added to the program, giving it an actionlistener:
Bravo = new JButton("Add 2 Faves");
Bravo.setBounds(460,0,130,20);
Bravo.addActionListener(this);
ButtonsAndText.add(Bravo);

C) Add another "else if" to our actionPerformed:
else if (e.getSource() == Bravo)
{
addFaves(); // make method call
}

D) create the new method that is being called

System.out.println("everybody, do the monkey!");
webURL.addElement(WhereTo.getText()); //add to vector
myWebPlaces = new JComboBox(webURL); //reload vector to combobox

That should about do it, And once you've mastered that, you know what I'm looking for:

1) add something you already know about to this program

2) make a posting about what you did today while working with this program

Have a helluva weekend,
Uncle Paulie

Wednesday, April 1, 2009

Friday April 3: Java Swing Tabbed Browsing part Five

Hey chilluns, I just had this sudden thought: what if we wanted to have a list of websites we could goto, instead of laboriously having to type in an address over and over? There are many ways of accomplishing this, and I suppose I COULD have made a menu; but I chose another path, for three reasons:


A) It would require having to make a MenuBar, Menu and several menuitems... too much work


B) We can accomplish the same goal using what's known in Java as a "ComboBox", aka a "pulldown menu". Plus, if we connect this ComboBox to a Vector (remember that component? Told you we'd use 'em again), it might be possible to make the list expand to hold more websites


C) I'm too old, too stubborn and too big to be prevented from using a ComboBox.


So anyway, here's how I did it, perhaps some of you have another idea. I would love to see them :-)


Add this import for using Vectors
import java.util.*; //for use with vectors

add these to your declarations section:
Vector webURL; //to hold addresses
JComboBox myWebPlaces; //to display those addresses

Add these two components to your constructor:
webURL = new Vector( );
webURL.addElement("http://www.google.com");
webURL.addElement("http://www.thinkgeek.com");
webURL.addElement("http://www.yahoo.com");
webURL.addElement("http://www.foxnews.com");

myWebPlaces = new JComboBox(webURL);
myWebPlaces.setEditable(true);
myWebPlaces.setBounds(300,0,100,20);
myWebPlaces.addActionListener(this);
ButtonsAndText.add(myWebPlaces);

Add this “else if” to your actionPerformed
else if (e.getSource( ) == myWebPlaces)
{
System.out.println(myWebPlaces.getSelectedItem());
StartPage= myWebPlaces.getSelectedItem()+ "";
makeTab( ); //call method, make new tab with selected page
}//end using combobox

Now obviously, if you want to use a different set of websites, or a different number of them, go right on ahead. Let's see what's in your fridge!

code is good food,
Uncle Paulie

Friday April 3: Java Swing Tabbed Browsing, part Four

Some of the sharper elements here may have noticed: hey, some websites are CUT OFF! I can't reach the bottom of the page! Wazzup wi' THAT?


Well, its true, a JeditorPane by itself will not scroll down to see all the stuff on a webpage that's too big to fit...that's why you need a "JScrollPane". What we will do is to put the JEditorPane which holds your webpage inside a JScrollPane which is added to the JTabbedPane which is added to a Container which is added to a JFrame.


Holy crap..supply lines are getting longer and harder to maintain!


Add this to your declarations
JScrollPane scrollTheWeb; //to make webpages scroll

Add this to the “try catch” in the method makeTab( ),

//put webpage container inside scroller
scrollTheWeb = new JScrollPane(newWeb);
scrollTheWeb.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

Just below where you have this line:
newWeb.setBounds(10,50,850,720);

and then change this line
Tabitha.add("Page " + pageNumber , newWeb);

To look like this
Tabitha.add("Page " + pageNumber , scrollTheWeb);

Shazzam!
Uncle Paulie

Tues April 1: Java Swing Tabbed Browsing, part Three

So now we can make tabs -- and LOTS of 'em!-- but they all display the same darned website! How's about we wanna choose our own site?



No problem-o... here's the way I did it. Perhaps you might have done it differently. This product sold by weight, not by volume...some settling of contents may have occurred during shipping :-)













Add this to your declarations section:
JTextField WhereTo;

Add these two components to your constructor:

Brain = new JButton("Go There");
Brain.setBounds(160,0,130,20);
Brain.addActionListener(this);
ButtonsAndText.add(Brain);

WhereTo = new JTextField(StartPage, 20); //starting page plus # of columns
WhereTo.setBounds(0,0,200,20);
WhereTo.addActionListener(this);
ButtonsAndText.add(WhereTo);

Add this “else if” to your actionPerformed:
else if (e.getSource() == Brain)
{
changePage( ); // make method call
}


Add this method just below the “makeTab( )” method
private void changePage( )
{
System.out.println("are you pondering what I'm pondering?");
StartPage = WhereTo.getText(); //set to addy in JTextField
makeTab( ); //call the other method, create new tab with new address
}//end method changePage

Tues April 1: Java Swing Tabbed Browsing, part Two

OK, so maybe you're thinking to yourself: this is cool but how do I make more than one tab? If I can't do that, it defeats the whole purpose of having tabs!



Very tru, O impatient ones, but there is a simple solution: create a button that calls the method that made the first tab. Try to see if you can figure that out on your own (I'm betting some of you already have). Try it yourself, and if you can't do it for real the solution is way down at the end of this posting



Cheers,

Uncle Paulie





















































































See, I told you I would give you a solution...now could you try doing this yourself next time?



Add this to your constructor:

Pinky = new JButton("New Tab");
Pinky.setBounds(0,0,130,20);
Pinky.addActionListener(this);
ButtonsAndText.add(Pinky);


Add this to your actionPerformed method

if (e.getSource( ) == Pinky)
{
makeTab( ); // make method call
}


Tues April 1: Java Swing Tabbed Browsing, part One

Greetings, fellow JavaNoidz!



In keeping with our ongoing exploration of Java Swing, today we will be looking at how to make a program that functions as a tabbed web browser. It's a little crude, but it will do to introduce you to several components we haven't explored yet, re-aquaint you with some items we haven't used in a while, and in general, do something both useful and k3wl.



To begin, download the program found at this address:

http://www.box.net/shared/pdhemt4r06



When you start it up, it won't look like much: a JFrame with a Container, a JPanel, which is like every Panel we've used before, etc etc. I've written in a lot of the declarations already, too.



The first thing we're going to do is to create a new component called a "JTabbedPane". It is exactly what it sounds like: a container with a little tab on top; it looks a lot like Firefox



Add this component to your constructor:
Tabitha= new JTabbedPane( );
Tabitha.setBounds(0,35,980,790);
ProvingGround.add(Tabitha);




next, add this method call inside your constructor...

makeTab( ); //set first tab by making method call

it'll call a method that will load a JEditorPane into the JTabbedPane we just created:



Since we're calling a method, we should make sure it exists too! Create this method just after your constructor:



private void makeTab( )
{
System.out.println("What are we gonna do tonight?");
//setup JEditorPane using try catch
try {
newWeb = new JEditorPane(StartPage);
newWeb.setEditable(false);
newWeb.setBounds(10,50,850,720);
Tabitha.add("Page " + pageNumber ,newWeb);
} //end try
catch(IOException ioe)
{
System.out.println("try and take over the world!");
} //end catch
pageNumber++; //increment int by one
} //end makeTab method




What this method does is to

A) create a JEditorPane

B) add it to a new Tab that is created which

C) is named after a String called "Page" plus an integer value which gets
"bumped up" by one at the end of the method


D) the tab includes the new JEditorPane object called newWeb



Cheers,

Uncle Paulie