Greetings JavaNoidz!
Well, its almost one of my favorite days, April 1, and to celebrate, I want to start this week off by looking at an updated version of Java called "swing". There's three things you should know right off the bat:
A) Everything in Swing is typed the same as in AWT, but with a "J" in front of it: JFrame, JButton, JTextField, etc etc
B) Swing components like JButtons are not loaded directly onto JFrames, but into "Containers"
C) There's some cool new things you can do in Swing that you can't do in AWT
OK, so let's get going. There's a folder online at Box.net that has two files in it: one a Java file which you will build on, the other being a small image file. Please download both from here:
http://www.box.net/shared/010jen6jjn
and put them into a folder named after yourself plus the word "swing"
When you load this program into TextPad, you will notice that there is a line of code that ends with "(EXIT_ON_CLOSE)" What this does is to close the JFrame AND shut down the program.
You will also notice that the JFrame has a Container object which will be used to hold components AND its layout has been set to "null". This allows you to position components exactly where you want them; BUT, you have to use the "setBounds" method for pretty much all of them. So OK, let's add a swing component and see it happen:
right below this line of code:
ProvingGround.setLayout(null);
add these lines:
JButton NewButton = new JButton("Look A JButton!");
NewButton.setBounds(0,0,165,65);
ProvingGround.add(NewButton);
compile it and run it, and you will see a button. No big deal; except, let's add another one and see if we can get something a little different:
ImageIcon buzzed = new ImageIcon("Feine.gif");
JButton PicButton = new JButton(buzzed);
PicButton.setBounds(100,200,195,65);
ProvingGround.add(PicButton);
ImageIcons can be used to add images to components, including, well JButtons. Notice that this image was found in the same folder as your program; if it was elsewhere, you'd need to somehow inform your program of this.
Let's try one more:
JButton ImageNtexT = new JButton("Wired", buzzed);
ImageNtexT.setBounds(300,100,165,65);
ProvingGround.add(ImageNtexT);
OK, for our next trick, let's look at doing some absolute positioning for the JFrame itself. Onward to the next posting!
Ubcle Paulie
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment