Last active
January 20, 2016 15:40
-
-
Save AnnaBoro/4e773a79c9c85cec94e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lesson5_8.Homework; | |
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.event.MouseEvent; | |
import java.awt.event.MouseListener; | |
import java.util.Random; | |
public class MagicSquare extends JPanel implements MouseListener { | |
private int randomPosition; | |
public MagicSquare() { | |
JFrame frame = new JFrame("MyMagicSquare"); | |
frame.setMinimumSize(new Dimension(500, 500)); | |
frame.setLocation(300, 100); | |
frame.getContentPane().add(this); | |
frame.addMouseListener(this); | |
frame.pack(); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.setVisible(true); | |
} | |
public static void main(String[] args) { | |
new MagicSquare(); | |
} | |
@Override | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
g.setColor(getRandomColor()); | |
g.fillRect(0, 0, 500, 500); | |
} | |
public Color getRandomColor() { | |
Color[] randomColors = {Color.GRAY, Color.BLUE, Color.RED, Color.YELLOW}; | |
randomPosition = -1; | |
Color randColor = randomColors[getRandomNum()]; | |
return randColor; | |
} | |
public int getRandomNum() { | |
Random random = new Random(); | |
int randomInt = random.nextInt(4); | |
if (randomPosition == randomInt) { | |
return getRandomNum(); | |
} | |
randomPosition = randomInt; | |
return randomInt; | |
} | |
@Override | |
public void mouseClicked(MouseEvent e) { | |
repaint(); | |
} | |
@Override | |
public void mousePressed(MouseEvent e) { | |
} | |
@Override | |
public void mouseReleased(MouseEvent e) { | |
} | |
@Override | |
public void mouseEntered(MouseEvent e) { | |
} | |
@Override | |
public void mouseExited(MouseEvent e) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment