Tuesday, March 31, 2009

Tuesday March 31: taste the HTML rainbow, part one

Greetings and salutations, fellow code jockeys!



Today, we shall continue onwards with an exploration of Java Swing; and the first step on this journey is to download the file located here:



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



The file inside is functional and will start up a JFrame with a pretty red background. It has an empty actionPerformed method, and its setup so that when you close the JFrame, you shut down the whole program. Beyond that, it doesn't do much; there's not even a component that could make anything happen. So let's change that right now, m'OK?



A) just below this line in the declarations section:

Container ProvingGround;

add this line to declare a JButton:

JButton Skittles;



B) In the constructor, just below this line:

ProvingGround.setLayout(null);

add this code block to create and enable the JButton you just declared:

Skittles = new JButton("Taste The Rainbow");
Skittles.setBounds(0,0,165,35); // null layout makes you use this
Skittles.setBackground(Color.blue);
Skittles.addActionListener(this);
ProvingGround.add(Skittles);




C) Finally, and most importantly, you have to add an if statement to your actionPerformed method, so that when you click the "Skittles" button, it pops up what's known as a JColorChooser Dialog. This dialog box allows you to choose a color, either by clicking on a box, or by setting integer values; you can then apply this color to the Container background:

if (e.getSource() == Skittles)

{

//pop up JColorChooser dialog box

Color TieDye = JColorChooser.showDialog(this,"Hey Man, the Colorz!", getBackground());

if (TieDye != null) //chose a color?

//change the Container Color to what you chose

ProvingGround.setBackground(TieDye);

}// end choose color Skittles button



PLEASE NOTE: the line that starts with "Color TieDye" got wrapped to the next line; please put both lines you see here on one line.



OK, that oughta do it; compile it and run, then see if it works for you.



Btw, if you somehow can apply the colors you find in this dialog at runtime, that would be cool. Not necessary, but cool.



Cheers,

Uncle Paulie

No comments:

Post a Comment