APCS SummerProject By Tim Reis

Using Colors, Graphics, 2D Shapes and Fonts in a Java Applet

Colors in a Applet

first you want to add your 3 import statements which will load the proper libraries required to use applet functionality

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

// Then you need to create the new class

public class SummerProjectAPCS extends JApplet implements ActionListener // Creating the class
JButton bgButton = new JButton("Set Bg Blue"); // Declaring the new JButton with text as "Set Bg Blue"

// Now to the initialize statement which will prepare the applet for display

public void init ()
setLayout(new FlowLayout()); // Creates the new FlowLayout which allows easier placement of objects on a Applet
add(bgButton); // This adds the button to the form
bgButton.addActionListener(this); // Adds the ActionListener to the Button so when it is clicked the applet will perform a task

// Now to the ActionPerformed method that will perform the task when the button is clicked

public void actionPerformed(ActionEvent e)

// Since we are using a FlowLayout you need to show java the object Pane(FlowLayout) then use the built in setBackGround method which will then set the background of the applet to a color of your choosing, for ex. blue, red, yellow.

// Lets go a step further and set the foreground color(text color) and use abstract colors from a RGB Color Chart.

// To set the forground color the statement above would be almost exactly the same except you would make,

getContentPane().setBackground(Color.blue); into getContentPane().setForeground(Color.blue); // Which would make all text blue

// Using Abstract Colors from a Color Chart

// We First need to declare a new variable which is a Color Variable it holds a specific color

private Color variableName = new Color(60,60,122); // The 3 Number sets are the color broken up by Red, Green, Blue

// now you would do;

getContentPane().setBackground(variableName); // and that would show the background as that color

// If you wanted to have multiple buttons and different events for each button you need to change up the methods a bit.

// Assuming you added your buttons to your Applet, I will show you the if statements required for multiple events.

public void actionPerformed(ActionEvent e)
if(e.getSource() == fgButton) // e is the ActionEvent Shown in above Line, getSource() finds the button.
texta.setForeground(Color.green); // The JLabel is texta, this sets the Foreground(text) of the JLabel to Green
if(e.getSource() == bgButton) // e is the ActionEvent Shown in above Line, getSource() finds the button.
getContentPane().setBackground(Color.blue); // Sets the background of the Applet to blue

// All Done

Next Page - Graphics