Question 2

import java.awt.*;

import java.awt.event.*;

import cs181.*;

 

public class Figures extends CloseableFrame {

private TextField currentFigure;

Color [] colours = {Color.red, Color.blue, Color.green};

private int currentColour = 0;

private int currentShape = 0;

private boolean mouseEntering = false;

public Figures () {

setTitle("Coloured Figures");

setBounds(150,100, 300,300);

setFont(new Font("SansSerif", Font.BOLD, 20));

currentFigure = new TextField("square",10);

Button nextColour = new Button("next colour");

nextColour.addActionListener(new ActionListener () {

public void actionPerformed (ActionEvent e) {

currentColour = (currentColour+1)%colours.length;

repaint();

}

});

Button nextShape = new Button ("next shape");

nextShape.addActionListener (new ActionListener () {

public void actionPerformed (ActionEvent e) {

currentShape = (currentShape+1)%2;

if (currentShape == 0) currentFigure.setText("square");

else currentFigure.setText("circle");

repaint();

}

});

addMouseListener (new MouseAdapter() {

public void mouseReleased (MouseEvent e) {

mouseEntering = true;

repaint();

}

});

Panel top = new Panel();

top.add(currentFigure);

add(top, "North");

Panel bottom = new Panel();

bottom.add(nextColour);

bottom.add(nextShape);

add(bottom, "South");

}

public void paint (Graphics g) {

if (mouseEntering){

g . setColor(Color.yellow);

mouseEntering = false;

}

else g.setColor(colours[currentColour]);

switch (currentShape) {

case 0: g.fillRect(100,100, 100, 100); break;

case 1: g.fillOval(100,100, 100, 100); break;

}

}

}

 

MAIN!!!~!~!~!~!

 

public class Main {

public static void main (String [] args) {

Figures win = new Figures();

win.setVisible(true);

}

}