AppletOne
The first applet example is a simple affair, it displays two labels with coloured backgrounds.
To get the background colour the applet takes two parameters passed in via the HTML page. We do this by using the following code:
<param name="colourOne" value="3">
And process them in the applet using this code;
String colourOne = getParameter("colourOne");
Note that the parameter passed is set as a string, if you want to convert it to another type (as we do) you need to cast it from a string.
Because we are using a 'switch' statement we need to convert the input into either an integer or single character input. This code casts the
string into an integer.
// cast parameter input to int for switch statement
int colOne = Integer.parseInt(colourOne);
Once we have our input ready, we pass it through the switch statement to set the label background. All that is left
to do now it create a layout to put the elements into and display them. There are many layouts that you can use,
this applet uses a grid layout. When you use this type of layout you need to declare the
rows and columns you want, then just add the elements to the layout.
// define layout
// setup container for grid layout
Container c = getContentPane();
// set rows, columns
c.setLayout(new GridLayout(1, 2));
// add elements to grid
c.add(jLabel1);
Now we have had a look at the code, lets have a look at the applet.
Stand-alone example here.
Source code for HTML page calling applet is here.
Source code for this applet is here.
AppletTwo
This applet does a similar thing to the previous one, but this time we are going to get the input from the user.
We are going to use a method from the swing library called JColorChooser.
This is a GUI element that allows the user to pick a colour from a palette. This also means we will need to add some
code to react to a button click (known as an event action listener). Also, in an effort to keep the code tidy, we
are going to keep all the source for this in a package. We do this by declaring it as a package at the start of the script.
package applets;
Next we need to create the buttons to be used.
jButton1 = new javax.swing.JButton();
Then code what will happen when it is clicked. This is where we will implement the JColorChooser, and set the background.
jButton1.addActionListener(new
java.awt.event.ActionListener()
{
// what to do when action, ie when clicked
public void actionPerformed(java.awt.event.ActionEvent evt)
{
// get colour from colour chooser
Color initialBackground = jButton1.getBackground();
Color background = JColorChooser.showDialog(null,
"JColorChooser Sample", initialBackground);
// if colur has been selected, set colour
if (background != null)
{
jLabel1.setBackground(background);
}
}
});
And below is the result of all this coding.
Stand-alone example here.
Source code for HTML page calling applet is here.
Source code for this applet is here.
Back to top