Basically I have an image loaded, and when I click a portion of the image, a rectangle (with no fill) shows up. If I click another part of the image again, that rectangle will show up once more. With each click, the same rectangle should appear.
So far I have this code, now I don't know how to make the image appear. My image from my file directory. I have already made the code to get the image from my file directory.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MP2 extends JPanel implements MouseListener{
JFrame frame;
JPanel panel;
int x = 0;
int y = 0;
String input;
public MP2(){
}
public static void main(String[] args){
JFrame frame = new JFrame();
MP2 panel = new MP2();
panel.addMouseListener(panel);
frame.add(panel);
frame.setSize(200,200);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent event) {
// TODO Auto-generated method stub
this.x = event.getX();
this.y = event.getY();
this.repaint();
input = JOptionPane.showInputDialog("Something pops out");
System.out.println(input);
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void paintComponent(Graphics g){
super.paintComponent(g);
// this.setBackground(Color.white); *Sets the bg color of the panel
g.setColor(new Color(255,0,0));
g.drawRect(x, y, 100, 100);
}
}
You may want to look at drawing the rectangle on The Glass Pane, as shown in GlassPaneDemo. For example, in paintComponent(), replace g.fillOval() with g.drawRect().
I don't know how to make the image appear.
This example shows how to display an image in a JLabel.
this.x and this.y refer to the x and y of your JPanel, not the rectangle you want to draw. You'll need to create two additional fields, rectX and rectY. These get set in mouseClicked and used by paintComponent().
EDIT
I'm sorry, my bad. I'm now confused. You do declare an x and y. These should still be renamed cause they can be confused with the x and y defined in Component, but they are not the problem. When I run your code and click, the red rectangle appears (along with a dialog). So I'm not sure what is the problem???
Related
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 can't animate spaceship.png nor update the image to animate it.
Need to animate it using paint method (could animate it using ImageIcons and labels) in order to rotate.
So, rewritten it but now i can't even update its' current position.
How can i make animation with a key listener ?
Why can't i animate the image that's being painted?
public class MyPanel extends JPanel implements KeyListener{
final int PANEL_WIDTH = 1920;
final int PANEL_HEIGHT = 1080;
Image spaceship;
Image spaceship2;
Image spaceship3;
Image Alien1;
Image Alien2;
Image AlienBoss;
Image Asteroid1;
Image Asteroid2;
Timer timer;
int xVelocity = 1;
int yVelocity = 10;
int x = 0;
int y = 0;
MyPanel(){
this.setPreferredSize(new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
this.setBackground(new Color(0x080e12));
this.addKeyListener(this);
spaceship = new ImageIcon("D:\\Users\\Xigmatek\\eclipse-workspace\\SpaceGameRev\\src\\spaceship.png").getImage();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(spaceship, x, y, null);
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case 87: x -=xVelocity;
repaint();
break;
case 83: x +=xVelocity;
repaint();
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Sorry if i have pasted too much of code but am kind of newbie so, sorry :/
The problem with the JPanel you created is that it is not focusable, i.e it does not register key events, it can be fixed with a simple line of code setFocusable(true), and I noticed that you update the frame only once the space ship moves, but it is always a good practice to update it once every 60'th of a second, or any frames per second, you can do this by implementing ActionListenerand passing the class to a Timer.
and I changed the keys to their respective variable(VK_W and VK_S)
Here is the updated code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
// in order to repeat after set delay, the class shall implement Action Listener and pass it to a timer(shown below)
public class MyPanel extends JPanel implements KeyListener, ActionListener {
final int PANEL_WIDTH = 1920;
final int PANEL_HEIGHT = 1080;
Image spaceship;
Image spaceship2;
Image spaceship3;
Image Alien1;
Image Alien2;
Image AlienBoss;
Image Asteroid1;
Image Asteroid2;
Timer timer;
int xVelocity = 1;
int yVelocity = 10;
int x = 0;
int y = 0;
MyPanel(){
this.setPreferredSize(new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
this.setBackground(new Color(0x080e12));
this.addKeyListener(this);
// set this JComponent focusable so that it can register keyEvents
setFocusable(true);
spaceship = new ImageIcon("res\\spaceship.png").getImage();
// pass this class to the timer to repeat after 1000/60 eth of a second(60 fps)
Timer timer = new Timer(1000/60, this);
timer.start();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(spaceship, x, y, null);
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// I changed 87 and 83 to their respective VK value
switch(e.getKeyCode()) {
case KeyEvent.VK_W: x -=xVelocity;
repaint();
break;
case KeyEvent.VK_S: x +=xVelocity;
repaint();
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
// Override this method from ActionListener
#Override
public void actionPerformed(ActionEvent e){
repaint();
}
}
Please watch this video, I demonstrated the output in this video.
By the way, you used w and s for horizontal movement(gamedev advice).
This is the MainApplication which creates a Frame and holds the class which implements Graphics.
MainApplication.java
import java.awt.*;
public class MainApplication
{
public MainApplication()
{
Frame frame= new Frame("Test App");
frame.add(new KeyTest());
frame.setBackground(Color.RED);
frame.setLayout(null);
frame.setSize(700,750);
frame.setVisible(true);
}
public static void main(String args[])
{
new MainApplication();
}
}
This class creates all the Graphical shapes and implements the KeyListener too.
KeyTest.java
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.RoundRectangle2D;
public class KeyTest extends Canvas {
/**
*
*/
private static final long serialVersionUID = 3L;
Graphics2D graphics2D;
Color color = Color.BLACK;
private static float borderThickness = 5;
Shape firstShape = new RoundRectangle2D.Double(20,40,300,50,10,10);
Shape secondShape = new RoundRectangle2D.Double(20,150,300,50,10,10);
public KeyTest()
{
setBackground(Color.RED);
setSize(700,750);
}
public void paint(Graphics graphics)
{
graphics2D = (Graphics2D)graphics; //TypeCasting to 2D
System.out.println("I am inside paint");
// Smoothening the corners
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Apple border color
Stroke oldStroke = graphics2D.getStroke();
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Apple
graphics2D.draw(firstShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(firstShape);
// Setting the font inside the shape
Font firstFont = new Font("Serif", Font.BOLD,35);
graphics2D.setFont(firstFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Apple",30,80);
// Pineapple border color
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Pineapple
graphics2D.draw(secondShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(secondShape);
// Setting the font inside the shape
Font secondFont = new Font("Serif", Font.BOLD,35);
graphics2D.setFont(secondFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Pineapple",30,190);
addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
System.out.println(KeyEvent.VK_UP);
if(keyCode==KeyEvent.VK_UP){
System.out.println("Going to move up");
move(firstShape);
}
if(keyCode==KeyEvent.VK_DOWN){
System.out.println("Going to move down");
move(secondShape);
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}});
}
public void move(Shape s){
System.out.println("Check:"+s.getBounds2D());
graphics2D.setColor(Color.GREEN);
graphics2D.fill(s);
System.out.println("moving out");
}
}
My console output clearly shows that my Key Listener works but its not executing the task which I intend it to do.
Console Output
I am inside paint Going to move up
Check:java.awt.geom.Rectangle2D$Double[x=20.0,y=40.0,w=300.0,h=50.0]
moving out Going to move down
Check:java.awt.geom.Rectangle2D$Double[x=20.0,y=150.0,w=300.0,h=50.0]
moving out
OUTPUT:
The Output which am getting now.. (IMAGE 1)
The output I expect when I press DOWN ARROW Button (IMAGE 2)
The Output I expect when I press UP ARROW Button (IMAGE 3)
First, you shouldn't add a KeyListener from inside the paint method, since it will register an additional one each time paint is called.
Then, don't rely on storing a Graphics object of a Componentand painting things on it, because many things can happen to it that are outside of your control (for instance it may get cleared by other occuring AWT UI operations).
The only relevant Graphics object is the instance you receive in paint, and only in the scope of the paint method.
So in the following code :
addKeyListener has been moved outside of paint .
The key listener
calls move with the index of the Shape to move.
The move method
now only registers the Shape to highlight depending on the index received, and calls repaint.
The
Graphics2D object is set as a local variable to paint, since it
isn't relevant outside.
paintHighlightedShape is responsible for painting the highlighted Shape, on a Graphics2D object received as a parameter
The paint method now calls paintHighlightedShape with its Graphics2D object passed as a parameter.
Note that a main method has been added to KeyTest for testing purpose, its content should go in your main class.
Also if you plan on having more Shapes to highlight, you may use an array of Shape, and the index passed to move could be the array index of the Shape to highlight.
Finally, to optimize things, we shouldn't draw the regular shape if it is a highlighted one, since it will be hidden by the green shape anyway.
Consider creating a drawShape(Graphics2D, Shape) method that will draw the regular shape or the green shape, depending on the shape being highlighted or not.
You would call this method from the paint method, looping on all shapes.
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.RoundRectangle2D;
public class KeyTest extends Canvas {
/**
*
*/
private static final long serialVersionUID = 3L;
Color color = Color.BLACK;
private static float borderThickness = 5;
Shape firstShape = new RoundRectangle2D.Double(20, 40, 300, 50, 10, 10);
Shape secondShape = new RoundRectangle2D.Double(20, 150, 300, 50, 10, 10);
Shape highlightedShape;
public KeyTest() {
setBackground(Color.RED);
setSize(700, 750);
}
public static void main(final String[] args) {
Frame frame = new Frame("Test App");
final KeyTest keyTest = new KeyTest();
keyTest.addKeyListener(new KeyListener() {
#Override
public void keyTyped(final KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(final KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyCode);
System.out.println(KeyEvent.VK_UP);
if (keyCode == KeyEvent.VK_UP) {
System.out.println("Going to move up");
keyTest.move(1);
}
if (keyCode == KeyEvent.VK_DOWN) {
System.out.println("Going to move down");
keyTest.move(2);
}
}
#Override
public void keyReleased(final KeyEvent e) {
// TODO Auto-generated method stub
}
});
frame.add(keyTest);
frame.setBackground(Color.RED);
frame.setLayout(null);
frame.setSize(700, 750);
frame.setVisible(true);
}
public void paint(final Graphics graphics) {
Graphics2D graphics2D = (Graphics2D) graphics; //TypeCasting to 2D
System.out.println("I am inside paint");
// Smoothening the corners
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Apple border color
Stroke oldStroke = graphics2D.getStroke();
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Apple
graphics2D.draw(firstShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(firstShape);
// Setting the font inside the shape
Font firstFont = new Font("Serif", Font.BOLD, 35);
graphics2D.setFont(firstFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Apple", 30, 80);
// Pineapple border color
graphics2D.setStroke(new BasicStroke(borderThickness));
graphics2D.setColor(Color.WHITE);
// Drawing a RoundedRectangle for Pineapple
graphics2D.draw(secondShape);
graphics2D.setStroke(oldStroke);
// Setting the Background Color
graphics2D.setColor(Color.BLACK);
graphics2D.fill(secondShape);
// Setting the font inside the shape
Font secondFont = new Font("Serif", Font.BOLD, 35);
graphics2D.setFont(secondFont);
graphics2D.setColor(Color.WHITE);
graphics2D.drawString("Pineapple", 30, 190);
paintHighlightedShape(graphics2D);
}
private void paintHighlightedShape(final Graphics2D graphics2D) {
if (highlightedShape != null) {
graphics2D.setColor(Color.GREEN);
graphics2D.fill(highlightedShape);
}
}
public void move(final int shapeNumber) {
switch (shapeNumber) {
case 1:
highlightedShape = firstShape;
break;
case 2:
highlightedShape = secondShape;
break;
default:
}
System.out.println("Check:" + highlightedShape.getBounds2D());
System.out.println("Moving shape : " + highlightedShape);
repaint();
System.out.println("moving out");
}
}
I would like to do this without the use of the JComponent. The idea is to have multiple buttons for each a shape, by clicking a button, I can then draw the shape for that button. Unfortunately, I can't even draw the shapes right now.
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton rect = new JButton("Rectangle");
ActionListener rListener = new RectangleNode();
rect.addActionListener(rListener);
MouseListener rMListener = new RectangleNode();
rect.addMouseListener(rMListener);
MouseMotionListener rMMListener = new RectangleNode();
rect.addMouseMotionListener(rMMListener);
JButton ellipse = new JButton("Ellipse");
JPanel panel = new JPanel();
panel.add(rect);
panel.add(ellipse);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setTitle("Graph Draw");
frame.setVisible(true);
}
The RectangleNode class
public class RectangleNode implements ActionListener,MouseListener,MouseMotionListener {
private Point p1;
private Rectangle r;
private boolean rdraw;
#Override
public void actionPerformed(ActionEvent e) {
rdraw = true;
}
#Override
public void mousePressed(MouseEvent e) {
if(rdraw = true){
p1 = e.getPoint();
r = new Rectangle(p1.x, p1.y, p1.x - p1.x, p1.y - p1.y);
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
if(rdraw = true){
int x = Math.min(p1.x, e.getX());
int y = Math.min(p1.y, e.getY());
int width = Math.abs(p1.x - e.getX());
int height = Math.abs(p1.y - e.getY());
r.setBounds(x, y, width, height);
repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(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
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.draw(r); ;
}
}
I'm not sure how to use repaint, and the paintComponent method in this situation.
Check out Custom Painting Approaches for an example of how to dynamically draw Rectangles.
In your case you want the ability to draw a Rectangle or an Ellipse so you would need to make some changes:
The Java API supports a Shape class. A Shape can be a Rectangle, Ellipse, Polygon etc. So you would need to change the "ColoredRectangle" class to a "ColoredShape" class. This would allow you to store a Rectangle or an Ellipse.
Then in the paintComponent() code you would need to change the drawRect(..) method to be a draw( Shape ) so you can draw both Rectangles and Ellipses.
In the mouseDragged() logic you would need to modify the logic to check if you want to draw a Rectangle or an Ellispse. Then you would create the proper Shape and again use the draw( Shape ) method instead of the drawRect(...) method.
Then you would need to add a property to the class to control which Shape you want to paint. Then when you click the button you set the property. Or maybe instead of using a button you set up radio buttons for each Shape.
Anyway, play with the original code to understand how it works. That is start by converting the code to use the ColoredShape class just for Rectangles. Then once that works you can add the support for the Ellipse.
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.