Java for Newbies - part 2
Hey GUIs, look here!
The last time we took a look at how to create a window with JFrame, and some text in the window with JLabel. Now let's explore some more GUI elements, and how to lay them out within the window.
First let's do some modifications to our code from last time, to prepare ourself for adding more elements into the mix.
Directly below the
add
This imports a class library that we'll need for some of our new code.
Then locate the following line and delete it
Now we are going to throw a button in there, by introducing the following code below the lane where we create our label.
JButton button = new JButton("Click me for luck!");
Now the quick ones might guess that by deleting the code that added the label to the frame, and not introducing any such code will make our label and button not to apear. You are right. We are going to introduce the JPanel. We will use the JPanel for aranging our elements in the frame, but also create some padding by implementing an "empty" border.
pane.add(label);
pane.add(button);
pane.setBorder(BorderFactory.createEmptyBorder(
20, //top
30, //left
10, //bottom
30) //right
);
frame.getContentPane().add(pane);
You see we add the label and the button to the JPanel, and then we use code similar to the one that used to put the label into the frame to put the JPanel into the frame. There's also a setBorder() method at play, that I don't think need further explanation.
If your code is like mine, you should get the following when hitting the "Run" button.

Text input
Let's quickly look at a couple of text field examples. After all there's not that many applications which don't accept any user input.
Bellow the button creation put the following code
JTextField textField = new JTextField(5);
//While we're at text fields let's make one that only accepts a decimal formated number
JFormattedTextField textField2 = new JFormattedTextField(
new java.text.DecimalFormat("##0.0#")
);
The first one should need no further explanation. The second one, the formatted text field, you use when you want to controll a legal set of characters that can be entered into the text field. I wont go in to the different formating methods and the different formatting mask characters at the moment.
I'll let you figure out how to add the text fields to the JPanel your self. But a click on the "Run" button should result in this (I've added some input in the text fields here):

I intented to go further, but time flys, and it's already time for bed :) So more GUI magic at a later time (very soon I promise).



