I am currently working on a 2D game which will be a puzzle. I got everything set up, got all my pieces added to my board (called View) and they're all aligned properly.
My next step is to select a piece by MouseEvent#mousePressed to be able to move it with the arrow keys with KeyEvent#keyPressed. The issue I'm currently running into is that my pieces will repaint themself whenever I move or resize the window. If I click on one piece and want to move it, the other pieces move too (in a way, they should not since one step equals about 100 pixel).
If anyone could tell me where my issue is and give me some advice, I would appreciate it.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Puzzle {
public static void main(String[] args) {
SwingUtilities.invokeLater(Puzzle::new);
}
public Puzzle() {
JFrame frame = new JFrame("Puzzle");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
View view = new View();
view.createPieces();
frame.setContentPane(view);
view.setFocusable(true);
MouseAdapterMod listener = new MouseAdapterMod(view);
view.addMouseListener(listener);
view.addKeyListener(listener);
frame.setVisible(true);
}
}
class View extends JPanel {
final List<Piece> pieces = new ArrayList<>();
public View() {
}
void createPieces() {
Piece topLeft = new Piece(100, 100, 0, Color.YELLOW);
pieces.add(topLeft);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gc = (Graphics2D) g;
for (Piece needle : pieces) {
needle.translate(needle.getLocation().x, needle.getLocation().y);
gc.setColor(needle.color);
gc.fill(needle);
gc.draw(needle);
}
}
}
class Piece extends Polygon {
int x;
int y;
final Color color;
Point location;
Piece(int x, int y, int type, Color color) {
this.x = x;
this.y = y;
this.color = color;
this.location = new Point(x, y);
int[] arrX = new int[] { 0, 100, 100, -100, -100, 0 };;
int[] arrY = new int[] { 0, 0, -100, -100, 100, 100 };
for (int drawIndex = 0; drawIndex < arrX.length; drawIndex++) {
addPoint(arrX[drawIndex], arrY[drawIndex]);
}
}
Point getLocation() {
return location;
}
void setLocation(Point location) {
this.location = location;
}
}
class MouseAdapterMod implements MouseListener, KeyListener {
final View view;
Polygon current;
public MouseAdapterMod(View view) {
this.view = view;
}
#Override
public void mousePressed(MouseEvent e) {
for (Piece piece : view.pieces) {
if (piece.contains(e.getX(), e.getY())) {
current = piece;
System.out.println(current);
}
}
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
current.translate(0, -100);
view.repaint();
break;
case KeyEvent.VK_DOWN:
current.translate(0, +100);
view.repaint();
break;
case KeyEvent.VK_LEFT:
current.translate(-100, 0);
view.repaint();
break;
case KeyEvent.VK_RIGHT:
current.translate(+100, 0);
view.repaint();
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
(Sorry for the indent, stackoverflow is messing it up)
EDIT: But the problem is, eventually I want to move my pieces using Piece#setLocation to always keep track of their current x/y coordinates. I figured, I need to invoke Piece#getLocation in my painting to draw them based on the location but yet I do not know how. Using Piece#setLocation literally does nothing.
If you revert back to your Piece code from this question, you can move pieces by:
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
view.translatePiece(0, -100);
break;
case KeyEvent.VK_DOWN:
view.translatePiece(0, +100);
break;
case KeyEvent.VK_LEFT:
view.translatePiece(-100, 0);
break;
case KeyEvent.VK_RIGHT:
view.translatePiece(+100, 0);
break;
}
}
And adding to your view:
void translatePiece(int dx, int dy) {
if (current != null) {
current.x += dx;
current.y += dy;
repaint();
}
}
The if (current != null) { ... } test will prevent your application from crashing if you press an arrow key before clicking on a piece, which it currently does.
You could, instead of translating the Polygon, translate the location, and use it for painting:
In keyPressed, replace current.translate to translate the location instead of the whole Polygon (you could override Piece#translate to call current.getLocation().translate for example).
In View#paintComponent, replace:
needle.translate(needle.getLocation().x, needle.getLocation().y);
with
gc.translate(needle.getLocation().x, needle.getLocation().y);
and add
gc.translate(-needle.getLocation().x, -needle.getLocation().y);
at the end of your for-loop.
This will translate the whole Graphics2D to paint a polygon, and revert it after.
Related
I have code which will draw circles depending on where the user clicks, and then will draw lines connecting those circles. I want to have the color of the circles and lines be set as Black by default, but the user can type either r,b,g,l (red, blue,green,black) to set the color of the NEXT circle and lines being drawn. What would I have to put inside of my KeyTyped method? I have if/else statements set up for whenever the user enters r,b,g, or l.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Circle extends JPanel implements MouseListener, KeyListener, MouseMotionListener {
private List<Point> points;
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Circle().buildAndDisplayGui());
}
public Circle() {
points = new ArrayList<>();
setPreferredSize(new Dimension(500, 500));
setBackground(Color.white);
addMouseListener(this);
}
private void buildAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addKeyListener(this);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
int count = points.size();
for (int i = 0; i < count; i++) {
Point pt0 = points.get(i);
g.fillOval(pt0.x - 10, pt0.y - 11, 20, 20);
if (i > 0) {
Point pt1 = points.get(i - 1);
g.drawLine(pt1.x, pt1.y, pt0.x, pt0.y);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
//Prints the coordinates of the clicks
System.out.println("X: " + e.getX() + " Y: " + e.getY());
Point pt = new Point(e.getX(), e.getY());
points.add(pt);
repaint();
}
#Override
public void mouseEntered(MouseEvent e) {
// Do nothing.
}
#Override
public void mouseExited(MouseEvent e) {
// Do nothing.
}
#Override
public void mousePressed(MouseEvent e) {
// Do nothing.
}
#Override
public void mouseReleased(MouseEvent e) {
// Do nothing.
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 'r') {
//Sets the color of the next circle and lines to red
} else {
if (e.getKeyChar() == 'b') {
//Sets the color of the next circle and lines to blue
} else {
if (e.getKeyChar() == 'g') {
//Sets the color of the next circle and lines to green
} else {
if (e.getKeyChar() == 'l') {
//Sets the color of the next circle and lines to black
}
}
}
}
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Current output:
Desired Output (If the user presses “r” after two mouse clicks and the does two more mouse clicks):
Add a Color instance variable to class Circle. In the example, I called it "currentColor". I set it to Color.black in the constructor.
Save a Color with each item in points. One way to do that is to have a parallel array. I don't like tightly coupled arrays, so I created a helper class in my example.
class PointAndColor {
Point thePoint;
Color theColor;
PointAndColor () {
theColor = Color.black;
thePoint = new Point (0,0);
}
PointAndColor (Point point, Color color) {
theColor = color;
thePoint = point;
}
Color getColor () { return theColor; }
Point getPoint () { return thePoint; }
}
I changed the generic type of the List of Points:
private List<PointAndColor> points;
private Color currentColor;
Example of saving the color with the point:
#Override
public void mouseClicked(MouseEvent e) {
//Prints the coordinates of the clicks
System.out.println("X: " + e.getX() + " Y: " + e.getY());
Point pt = new Point(e.getX(), e.getY());
points.add (new PointAndColor (pt, currentColor));
repaint();
}
Set the current color in the keyTyped method
#Override
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case 'r':
currentColor = Color.red;
break;
case 'g':
currentColor = Color.green;
break;
case 'b':
currentColor = Color.blue;
break;
case 'l':
currentColor = Color.black;
break;
default:
break;
}
System.out.println ("Color set to " + currentColor);
}
Retrieve the Color with the Point:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int count = points.size();
for (int i = 0; i < count; i++) {
Point pt0 = points.get(i).getPoint();
g.setColor (points.get(i).getColor());
g.fillOval(pt0.x - 10, pt0.y - 11, 20, 20);
if (i > 0) {
Point pt1 = points.get(i - 1).getPoint();
g.drawLine(pt1.x, pt1.y, pt0.x, pt0.y);
}
}
}
Guys I'm trying to create a 2d basic game for my homework the game rules are easy and simple which is there are 2 images (ball and droplets) if you click on the ball it will give us +2 points and if you click on droplets it will give us +1 points but if droplets reach the ground we lose -5 points so we need to click on droplets as much as we can and the ball can hit the borders of the frame it will bounce back and my teacher want from me to add menuBar with different menuItem which I did there is no problem with that
But I can't figure out how to add mouse listener to an image I tried to turn them into a Label but this time I had another problem which is how to print a label they're not string or line or shape or 2d objects
So this is the code that I wrote
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener,MouseListener {
/*dx = droplet's x position, dy = droplet's y position
*bx = ball's x position, by = ball's y position
*/
int dxPosition,dyPosition;
int ballVelocity,dropletVelocity;
int bxPosition,byPosition;
boolean ballToRight,ballToDown;
boolean dropletToDown;
int result;
Image droplet,ball;
Font lifeFont;
JTextField txtLife;
int lifePoint = 10;
Timer timer;
public Game() {
setLayout(null);
lifeFont = new Font("TimesRoma",Font.ITALIC,30);
txtLife = new JTextField("Life Points: "+lifePoint);
txtLife.setFont(lifeFont);
txtLife.setEditable(false);
txtLife.setBounds(0,720,8000,50);
txtLife.setOpaque(true);
txtLife.addMouseListener(this);
add(txtLife);
//Adding the images
droplet = new ImageIcon("droplet.png").getImage();
ball = new ImageIcon("ball.png").getImage();
ballVelocity = 10;
dropletVelocity = 10;
timer = new Timer(30,this);
timer.start();
setSize(800,800);
setBackground(Color.DARK_GRAY);
setVisible(true);
}
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
//Creating and putting the 2D images on the panel
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(ball, bxPosition, byPosition, this);
g2D.drawImage(droplet, dxPosition, dyPosition, this);
}
public static void main(String[] args) {
Game animateGame = new Game();
JFrame myFrame = new JFrame("Game Play");
myFrame.setSize(animateGame.getSize());
myFrame.setVisible(true);
myFrame.setLocationRelativeTo(null);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(animateGame);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource().equals(timer)) {
//When the timer start call these methods to work
ballHorizontal();
ballVertical();
dropletVertical();
}
//and repainted it
repaint();
}
public void ballHorizontal() {
if(bxPosition<750 && ballToRight == true)
bxPosition += ballVelocity;
else if(bxPosition>2){
ballToRight = false;
bxPosition -= ballVelocity;
}
else
ballToRight = true;
}
public void ballVertical() {
if(byPosition<665 && ballToDown==true)
byPosition += ballVelocity+2;
else if(byPosition>15){
ballToDown = false;
byPosition -= ballVelocity;
}
else
ballToDown = true;
}
public void dropletVertical() {
if(dyPosition<665 && dropletToDown==true)
dyPosition += dropletVelocity;
else if(dyPosition>15){
dropletToDown = false;
dyPosition -= dropletVelocity;
}
else
dropletToDown = true;
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getSource().equals(txtLife))
lifePoint += 2;
txtLife.setText("Life Points: "+ lifePoint);
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
These are the photos of the current version
My question is how can I make it change whenever I click the ball or droplet it will give me extra life points, when droplet and ball collide it will reduce life points and when droplets hit the ground it will reduce life points as well so when we click to droplet it will disappear and start falling over from somewhere in the x coordinate
I got the snake running down, now I try to get the keypressed() method to work. I don't think it's listening from the keyboard. My idea is for example if the the down key is pressed, the variable direction is set to 1 and the switch case statement would handle that. I doubt that the direction variable was't read by the switch case.
My main class:
package com.bin.snake;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel{
boolean playingSnake = true;
Snake snake = new Snake();
public Game() {
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
snake.keyPressed(e);
}
});
setFocusable(true);
}
public void paint(Graphics g) {// inherit paint method of JPanel class with
// parameter g type Graphics
// parameter g is the object to paint things
super.paint(g); // erase latest image
Graphics2D g2d = (Graphics2D) g; // casting g to Graphics2D type
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// rendering
// image
snake.paint(g2d);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Snake!");
frame.setVisible(true);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Game game = new Game();
frame.add(game);
while (true) {
game.updateGame();
game.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void updateGame() {
snake.moveSnake();
}
}
My Snake Class:
package com.bin.snake;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
public class Snake {
private Game game;
int iSnakeLength = 10;
int direction = 1;
final int SIDE = 13;
int[] snakeY = new int[2000];
int[] snakeX = new int[2000];
int xs = 0;
int ys = 0;
public void moveSnake() {
switch (direction) {
case 0:// up
snakeY[0] -=1.5;
break;
case 1:// down
snakeY[0] += 1.5;
break;
case 2:// right
snakeX[0] += 1.5;
break;
case 3:// left
snakeX[0] -=1.5;
break;
}
for (int i = iSnakeLength; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
}
public void paint(Graphics2D g) {
g.fillRect(snakeX[0], snakeY[0], SIDE, SIDE);
for (int i = 0; i < iSnakeLength; i++) {
g.fillRect(snakeX[i + 1], snakeY[i + 1], SIDE, SIDE);
}
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_DOWN){
direction = 1;
}
if(e.getKeyCode() == KeyEvent.VK_UP){
direction = 0;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
direction = 3;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
direction = 2;
}
}
}
I don't think it's listening from the keyboard. My idea
KeyEvents are only dispatched to the component with focus. A JPanel is not focusable by default.
To make a panel focusable you use:
panel.setFocusable( true );
Other comments:
Custom painting is done by overriding the paintComponent(...) method, not the paint() method. Read the Swing tutorial on Custom Painting for more information and examples.
You should NOT be using a KeyListener. Swing was designed to be used with Key Bindings. Read the Swing tutorial on How to Use Key Bindings. You can also check out Motion Using the Keyboard which contains working examples of moving a component using Key Bindings.
For animation you should be using a Swing Timer to schedule the animation. Check the table of contents from the tutorial links I have already provided. There is a section on How to Use Swing Timers.
I'd like to make something similar to a cursor, ( I get no errors )
So basically I get the coordinates once I enter the applet, and based on them I have my image drawn.
Here's the code... Can you please tell me where I'm wrong ? Thanks
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Z_applets extends Applet implements
KeyListener, MouseListener, MouseMotionListener {
int z = 100;
int t = 100;
// boolean gigel = true;
//----------------- Images
Image image;
//-----------------
//----------------- Mouse Coordinates
Point p = null;
int x;
int y;
//----------------------------------
Color color = Color.GREEN;
public void init() {
addKeyListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
setBackground(Color.BLACK);
g.setColor(color);
g.drawImage(image, x, y, this);
g.fillOval(z, t, 15, 15);
}
public void update(Graphics g) {
paint(g);
}
public void loadImage() {
//URL url = getClass().getResource("borat.jpg");
//image = getToolkit().getImage(url);
try {
URL url = new URL(getCodeBase(), "trollface.png");
System.out.println(getCodeBase());
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("error" + e.getMessage());
}
}
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
char option;
option = ke.getKeyChar();
switch (option) {
case 'w': {
t--;
repaint();
break;
}
case 's': {
t++;
repaint();
break;
}
case 'a': {
z--;
repaint();
break;
}
case 'd': {
z++;
repaint();
break;
}
case '1': {
color = Color.GREEN;
break;
}
case '2': {
color = Color.RED;
break;
}
case '3': {
color = Color.YELLOW;
break;
}
// case 'r':
// {
// loadImage();
// repaint();
// break;
// }
}
}
#Override
public void keyReleased(KeyEvent ke) {
}
#Override
public void mouseClicked(MouseEvent me) {
// p = me.getPoint();
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mouseEntered(MouseEvent me) {
// p=me.getPoint();
//-------Debug--------
System.out.println(p);
System.out.println(p.x);
System.out.println(p.y);
//----------------------
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent me) {
p = me.getPoint();
x = p.x;
y = p.y;
repaint();
}
}
Without knowing what problem you have exactly, I suppose the image isn't being moved.
I looks you don't register a MouseMotionListener so do that and implement the mouseMoved method.
I've created a basic Java program that creates a rectangle on startup and every time it is clicked, the rectangle grows and changes to a different (random) color. here's my code:
package rectPAK;
import javax.swing.JFrame;
public class DisplayRect {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(0,0,1000,1000);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
and then myCanvas is this:
package rectPAK;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.JComponent;
public class MyCanvas extends JComponent{
int W = 100;
int H = 100;
int r;
int g;
int b;
int trans;
int maxRandNum = 255;
int xPoint;
int yPoint;
public MyCanvas() {
this.addMouseListener(m);
this.addMouseMotionListener(ml);
}
Random rand = new Random();
MouseListener m = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
W = W + 20;
H = H + 20;
r = rand.nextInt(maxRandNum);
g = rand.nextInt(maxRandNum);
b = rand.nextInt(maxRandNum);
trans = rand.nextInt(maxRandNum);
repaint();
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
};
MouseMotionListener ml = new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
Point p = e.getLocationOnScreen();
xPoint = p.x;
yPoint = p.y;
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
};
public void paint(Graphics gr) {
gr.setColor(Color.BLACK);
gr.drawRect(xPoint, yPoint, W, H);
gr.setColor(new Color(r,g,b,trans));
gr.fillRect(xPoint, yPoint, W, H);
}
}
now my question is this: how do i make it so that when i right-click on the rectangle, it reverts to the previous size and color? i Know it's a lot to ask, but i cant find anything about it...
Thanks a lot.
Use a set of "previous" variables (eg previousX, previousY, previousR, etc) to store the old info before every update, and create a right click event to call a method like your paint method to set the object's variables to previousX, previousY, etc.
Every time you generate a random number, store it as the previous instance. This way you will be able to go back one step. If you want to go back all the way to the first one, then you should store each created rectangle's parameters in an stack of sorts, where you could pop out each previous stage.
Once that is done you should create a method for handling right clicks, and in that method, you should set the rectangles parameters to the previous value.