Grammar Gorilla
Coding Begins
1. This program creates 3 Buttons that changes the background of the window when pressed. Your job is to compile and run this program.
2. Then go to the Sun Tutorial/Big Index JFC/Swing Laying Out Components within a Container to learn how to use the various Layout Managers. For the Grammar Gorilla Project we need a page with 4 buttons placed on the bottom of the page; one for back, one for forward one for home and one for exit.
3. Expand on this Button exercise to create such a page.
4.
Continue
to expand this page to allow for user input in checkboxes for “a” through “d”
possible answers.
5.
This
program will become the foundation of the GUI for the Grammar Gorilla. Keep in mind that
your solution will need to be testing on more than one page and that you may divide up the work amongst
yourselves however you like.
Good Luck
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest
{
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
// New Class Button Frame
import javax.swing.JFrame;
/**
A frame with a button panel
*/
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
ButtonPanel panel = new ButtonPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
// New Class Button Panel
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
/**
A panel with three buttons.
*/
class ButtonPanel extends JPanel
{
public ButtonPanel()
{ // create buttons
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
// add buttons to panel
add(yellowButton);
add(blueButton);
add(redButton);
// create button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.red);
// associate actions with buttons
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
/**
An action listener that sets the panel's background color.
*/
private class ColorAction implements ActionListener
{
public ColorAction(Color c)
{
backgroundColor = c;
}
public void actionPerformed(ActionEvent event)
{
setBackground(backgroundColor);
}
private Color backgroundColor;
}
}