Color Changer 1.0
Complete Source
Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/* This program will open a GUI window in which a
user will be allowed to continuously change the
background color of the display area simply by clicking designated squares
on the screen. The
choices for color are red, green, and yellow. This program will also keep
track of the number
of times each square is clicked. */
public class ColorChanger {
public static JFrame myFrame;
public static ColorChangerPanel myPanel;
public static int redCount;
public static int greenCount;
public static int yellowCount;
public static class ColorChangerPanel
extends JPanel {
public void paintComponent(Graphics g) {
String rCount =
Integer.toString(redCount);
String gCount =
Integer.toString(greenCount);
String yCount =
Integer.toString(yellowCount);
Font font;
super.paintComponent(g);
font = new Font("Courier",
Font.BOLD, 18);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString("Click on the
squares below.", 50, 30);
g.setColor(Color.RED);
g.fillRect(75,60,40,40);
g.setColor(Color.BLACK);
g.drawRect(75,60,40,40);
g.drawString(rCount,80,85);
g.setColor(Color.GREEN);
g.fillRect(175,60,40,40);
g.setColor(Color.BLACK);
g.drawRect(175,60,40,40);
g.drawString(gCount,180,85);
g.setColor(Color.YELLOW);
g.fillRect(275,60,40,40);
g.setColor(Color.BLACK);
g.drawRect(275,60,40,40);
g.drawString(yCount,280,85);
g.drawString("\u00A9", 85,
360);
font = new Font("Courier",
Font.PLAIN, 14);
g.setFont(font);
g.drawString("2011 by Dilip
Muthukrishnan", 103, 360);
}
}
public static class ColorChangerMouse
implements MouseListener {
public void mousePressed(MouseEvent e) {
ColorChangerPanel source = (ColorChangerPanel)
e.getSource();
if ((e.getX() > 75 && e.getX()
< 115) && (e.getY() > 60 && e.getY() < 100)) {
redCount++;
source.setBackground(Color.RED);
source.repaint();
}
if ((e.getX() > 175 && e.getX()
< 215) && (e.getY() > 60 && e.getY() < 100)) {
greenCount++;
source.setBackground(Color.GREEN);
source.repaint();
}
if ((e.getX() > 275 && e.getX()
< 315) && (e.getY() > 60 && e.getY() < 100)) {
yellowCount++;
source.setBackground(Color.YELLOW);
source.repaint();
}
}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {
ColorChangerPanel source = (ColorChangerPanel)
e.getSource();
source.setBackground(Color.WHITE);
}
}
public static void main(String[]
args) {
myFrame = new JFrame("ColorChanger");
myPanel = new ColorChangerPanel();
redCount = 0;
greenCount = 0;
yellowCount = 0;
myPanel.setBackground(Color.WHITE);
myPanel.addMouseListener(new ColorChangerMouse());
myFrame.add(myPanel);
myFrame.setSize(416,438);
myFrame.setLocation(100,100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
} |