left-click revert - rectangle, mouseClickedEvent - java

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.

Related

How to add MouseListener to an Image and make the Image move in JPanel

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

Painting in multiple classes

I am not very good with using multiple classes in java, as I've always found it easier to do all of my code in 1 class. Recently I've found the need to use a second class for a game I'm making and I'm running into an error.
Right now I'm just trying to spawn the enemy where and when the user clicks.
Main Class -
package joey.rts;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class RTSMain extends JFrame implements MouseListener{
/**
*
*/
private static final long serialVersionUID = -7122370886923000314L;
public static BufferedImage menu,enemy;
public static boolean onmenu,oneenemy;
public static void main(String[] args){
new RTSMain();
}
public RTSMain(){
init();
}
public void init(){
setSize(1700,1100);
setVisible(true);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("RTS");
addMouseListener(this);
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
if(onmenu == true){
g2.drawImage(menu,0,0,this);
}
}
#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
}
#Override
public void mousePressed(MouseEvent e) {
Enemy enemy = new Enemy();
int x = e.getX();
int y = e.getY();
enemy.spawnEnemy(x, y);
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
Enemy class -
package joey.rts;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Enemy{
/**
*
*/
public static BufferedImage enemy;
private static final long serialVersionUID = 7898827977636314494L;
public static RTSMain rts;
public static void main(String[] args){
try{
enemy = ImageIO.read(new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "\\enemy.png"));
} catch (Exception e){
e.printStackTrace();
}
}
public static void spawnEnemy(int x, int y){
Graphics g = rts.getGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(enemy,x,y,null);
}
}
In your Main class update your mouseClicked function to be :
#Override
public void mouseClicked(MouseEvent e) {
Enemy enemy = new Enemy();
int x=e.getX(); // get mouse positionX
int y=e.getY();//get mouse positionY
enemy.spawnEnemy(x,y);//spawn Enemy
}
Consider saving the enemy objects if you need to reuse it later.
Also I see no need to extend anything in Enemy Class.
I've Updated Your Main and your Enemy class :
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Main extends JFrame implements MouseListener{
/**
*
*/
private static final long serialVersionUID = -7122370886923000314L;
public static BufferedImage menu,enemy;
public static boolean onmenu,oneenemy;
public static void main(String[] args){
new Main().setVisible(true);
}
public Main(){
init();
}
public void init(){
setSize(1700,1100);
setVisible(true);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("RTS");
addMouseListener(this);
}
#Override
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
if(onmenu == true){
g2.drawImage(menu,0,0,this);
}
}
#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
}
#Override
public void mousePressed(MouseEvent e) {
Enemy enemy = new Enemy();
int x = e.getX();
int y = e.getY();
enemy.spawnEnemy(x, y,this.getGraphics());
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
And this is the Enemy class :
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class Enemy{
public static BufferedImage enemy;
private static final long serialVersionUID = 7898827977636314494L;
public Enemy(){
try {
//MAKE SURE THAT THIS IS THE CORRECT IMAGE PATH
enemy = ImageIO.read(new File(javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory() + "\\enemy.png"));
} catch (IOException ex) {
Logger.getLogger(Enemy.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void spawnEnemy(int x, int y,Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(enemy,x,y,null);
}
}
I've removed the instance variable of Main that was on Enemy class.
I've removed the static modifier for the spawnEnemy function.
I've sent the graphics object as an attribute to spawnEnemy function .
I've Moved the code that was in main method in Enemy class to the Enemy Constructor.
Hope it helps !
It just seemed easier to paste an answer than to try to explain it in a comment. Your OO is a bit off. Add this to your RTSMain class:
protected ArrayList<Enemy> enemies = new ArrayList<Enemy>();
protected BufferedImage enemyImage = null;
...
public void init() {
...
// everything you already have...
enemyImage = //read in your enemy image here
...
}
...
#Override
public void mouseClicked(MouseEvent e) {
// this takes place of Enemy.spawn(), get rid of it
int x = e.getX(); // get mouse positionX
int y = e.getY(); //get mouse positionY
Enemy enemy = new Enemy( enemyImage, x, y );
Enemies.add( enemy );
// Iterate over list above to draw each enemy in your paintComponent method
}
Also, JFrame doesn't have a paintComponent() method, which you need to override to do your painting (paint() is deprecated). Add a JPanel, override it's paintComponent() and so on. For a game, you'll probably want to create a game loop to do your painting, unless it's very turn-based.
Happy coding.

Calling a graphics method inside a keylistener

So for my AP Comp. science class I have to make an applet where we have to use separate class files to make a building skyline-line thing. At the moment I have a window class that has a draw method and a method to turn the window object on. I would like to have the window turn on with a keyListener, but I'm semi-new to those.
this is the Window class I have
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JComponent;
public class windows {
private int x,y,height,width;
public windows(){
x=0;
y=0;
height = 0;
width = 0;
}//default constructor
public windows(int x, int y, int height, int width){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}//windows constructor
public void windowDraw(Graphics g){
Color window = new Color(0x05030D);
g.setColor(window);
g.fillRect(x, y, width, height);
}//windowDraw
public void windowOn(Graphics g){
Color on = new Color(0xFFD200);
g.setColor(on);
g.fillRect(x, y, width, height);
}//window on
}//class
Here is the client. I have some test prints inside that I used to play around with.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
//Matteo Sabato
public class TeenTitans_Client extends Applet implements KeyListener {
private final int APPLET_WIDTH = 1000;
private final int APPLET_HEIGHT = 700;
private final int HEIGHT_MIN = 400;
private final int VARIANCE = 40;
Tower main,top;//(x, y, height, width)
backGround ground;//x,y,height,width
windows Right, middleTop, Left, Bottom, Middle, Tip;
boolean power = false;
Listener on;
int key;
public void init(){
addKeyListener(this);
Random gen = new Random();
Color back = new Color(0x37E2EA);
setBackground(back);
setSize(APPLET_WIDTH,APPLET_HEIGHT);
main = new Tower(550,180,460,150);
top = new Tower(370,40,150,505);
ground = new backGround(-200,500,400,1800);
Right = new windows(380,50,130,130);
Left = new windows(735,50,130,130);
middleTop = new windows(520,50,130,205);
Bottom = new windows(560,490,140,130);
Middle = new windows(560,340,140,130);
Tip = new windows(560,190,140,130);
}
public void paint(Graphics g){
ground.circleDraw(g);
main.towerDraw(g);
top.towerDraw(g);
Left.windowDraw(g);
Right.windowDraw(g);
Bottom.windowDraw(g);
middleTop.windowDraw(g);
Middle.windowDraw(g);
Tip.windowDraw(g);
if (power == true)
On(g);
}//paint
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub.
System.out.println(e.getKeyCode());
this.key = e.getKeyCode();
if (key==10){
power = true;
}
}//keyPressed
public void On(Graphics g){
Tip.windowOn(g);
}//On
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}//class
The problem I'm running into is that I don't know how to call my On method in the client because I need to have Graphics g as a parameter, which key event methods can't take. If I make a loop somewhere else, I won't be able to check for key presses. I tried laying it out a bunch of different ways, but I just can't figure it out.

How to move and object in a straight line with consistent speed

I am trying to move a circle in a straight line. But my Code is not giving expected results. I m using mouseMotionListener to constantly get the target points and x_pos and y_pos are co-ordinated for my circle. I am using trigonometric function sin cos and atan, to move the object in straight line --its a logic i have seen here from a question posted on stack overflow--
but it is not giving me the expected results, am i doing something wrong plz help:
import java.awt.Graphics;
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.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
public class Snake extends JPanel {
static Snake snake = new Snake();
static Co_Ordinates co = new Co_Ordinates();
static int x_pos = 10, y_pos = 500;
static int slope;
int delta_x,delta_y;
double direction;
double x_inc,y_inc;
public Snake() {
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(Color.green);
g2d.fillArc(x_pos, y_pos, 20, 20, 0, 360);
try {
Thread.sleep(10);
} catch (Exception e) {
}
/*if(x_pos==co.x_Cur){
if(co.y_Cur>=y_pos)
y_pos++;
else if(co.y_Cur<=y_pos)
y_pos--;
}
else if(y_pos==co.y_Cur){
if(co.x_Cur>=x_pos)
x_pos++;
else if(co.x_Cur<=x_pos)
x_pos--;
}
*/
//slope=((co.y_Cur - y_pos) / (co.x_Cur - x_pos));
//y_pos = slope*x_pos+y_pos;
//x_pos++;
//System.out.println("...");
if(x_pos!=co.x_Cur&&y_pos!=co.y_Cur){
int delta_x = co.x_Cur - x_pos;
int delta_y = co.y_Cur - y_pos;
direction = Math.atan(delta_y / delta_x); // Math.atan2(deltaY, deltaX) does the same thing but checks for deltaX being zero to prevent divide-by-zero exceptions
double speed = 5.0;
x_inc = (speed * Math.cos(direction));
y_inc = (speed * Math.sin(direction));
x_pos+=x_inc;
y_pos+=y_inc;
}
//x_pos = co.x_Cur;
repaint(10);// parameters
}
public void move() {
}
public static void main(String args[]) {
JFrame jf = new JFrame();
jf.add(co);
jf.addMouseMotionListener(co);
jf.addMouseListener(co);
jf.add(snake);
jf.setSize(600, 600);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
class Co_Ordinates extends JPanel implements MouseMotionListener, MouseListener {
static int slope;
static Snake sn = new Snake();
static int x_Cur=sn.x_pos-20;
static int y_Cur=sn.y_pos-40;
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
x_Cur = e.getX() - 20;
y_Cur = e.getY() - 40;
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}// Class Listener ends here
In the code where you used Math.atan should be changed to Math.atan2.
atan only gives angle values between -90deg and 90deg.
atan2 gives angle values between -180deg and 180deg.
I have modified that part of the code as below.
First, change atan to atan2
Second, make the speed become zero if the circle meets the mouse pointer (the target?)
Third is a minor one but, you don't need the if-condition unless performance is critical.
Please try with this one.
// if(x_pos!=co.x_Cur&&y_pos!=co.y_Cur){
delta_x = co.x_Cur - x_pos;
delta_y = co.y_Cur - y_pos;
direction = Math.atan2(delta_y, delta_x);
double speed = Math.sqrt(delta_x*delta_x + delta_y*delta_y);
speed = Math.min(speed, 5.0);
x_inc = (speed * Math.cos(direction));
y_inc = (speed * Math.sin(direction));
x_pos+=x_inc;
y_pos+=y_inc;
//}

How do I make a rectangle move in an image?

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???

Categories