Why is my KeyPressed method never called? - java

I am trying to write my first PacMan game. So I followed a guide and created a small game engine and now I am writing code in the PacMan.java file which includes the game engine as a package. The problem is, the guide instructs you to override the KeyPressed method, but when I do this NOTHING happens. The PacMan on the screen is supposed to change its direction according to what arrowkeys I press according to the KeyPressed() method but when I press the arrowkeys NOTHING happens. I can't control the little pacman through the arrowkeys even though I have the code for it!
I even put a simple System.out.println(); statement inside the KeyPressed() method to see if the KeyPressed() method is even ever actually called, but it is NEVER called it seems? "pressed the key" isn't being printed out when I press the arrowkeys and neither is the PacMan moving when I press them. Can anyone understand why my KeyPressed method won't be called when I press my arrowkeys?
My code:
package game.pacman;
import org.game.engine.Game;
import org.game.engine.GameApplication;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class PacMan extends Game {
public static void main(String[] args){
GameApplication.start(new PacMan());
}
BufferedImage pacman;
int frame;
int dir;
int x, y;
final int STEP = 2;
public PacMan(){
title = "PacMan";
frame = 0;
dir = KeyEvent.VK_RIGHT;
x = 300;
y = 200;
width = height = 400;
try {
pacman = ImageIO.read(new File("images/packman.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void keyPressed(KeyEvent e){
System.out.println("pressed the key");
dir = e.getKeyCode();
}
#Override
public void update(){
frame++;
if (frame > 2){
frame = 0;
}
switch (dir){
case KeyEvent.VK_LEFT:
x -= STEP;
break;
case KeyEvent.VK_RIGHT:
x += STEP;
break;
case KeyEvent.VK_UP:
y -= STEP;
break;
case KeyEvent.VK_DOWN:
y += STEP;
}
if ( x < 0){
x = 0;
} else if (x > width-28-STEP){
x = width-28-STEP;
}
}
#Override
public void draw(Graphics2D g) {
g.drawImage(pacman.getSubimage(frame*30,(dir-37)*30,28,28), x, y, null);
}
}
Obviously it is supposed to override (through the package) a method KeyPressed inside a class Game.java inside the game engine which implements KeyListener, MouseListener, MouseMotionListener. Here is the whole code code for that class:
package org.game.engine;
import java.awt.*;
import java.awt.event.*;
public abstract class Game implements KeyListener, MouseListener, MouseMotionListener{
protected boolean over;
protected int delay = 30;
protected int width = 400;
protected int height = 400;
protected String title = "MyGame";
public String getTitle(){
return title;
}
public long getDelay(){
return delay;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public void init(){}
abstract public void update();
abstract public void draw(Graphics2D g);
public boolean isOver(){
return over;
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
So as you can see the KeyPressed() method is just empty inside the class and this is how the guide instructs it to be. I am overriding it in the PacMan class (my main class). So why isn't either the arrow keys working, why isn't even the KeyPressed method being called at all when I run the program? Is something missing to call the KeyPressed() method?

Though you implement the handlers in Game class and ovveride them in subclass, you haven't registered the handler to the element you want.
For ex, inside Game class,
something.onKeyPress(this)
// where this is Game class which is of type KeyListener, MouseListener, MouseMotionListener

you have to register component with Key-Listener for that do likewise,
If your component is JTextField then it should be likewise,
JTextField typingArea = new JTextField(20);
typingArea.addKeyListener(this);
while press key inside, typingArea - JTextField it will called this method too,
public void keyPressed(KeyEvent e) {
displayInfo(e, "KEY PRESSED: ");
}

Related

Trouble with drawing a moving paddle for pong flawlessly using Netbeans

I am trying to make Pong. I sent this program to a friend and when he ran it the first time he got my bug but later it ran fine. I always seem to get the bug. My paddle can move up and down. It seems to move correctly and it gets drawn in the right place but it always flickers to the start position and back again. It looks like it gets drawn once at the start position and then at the right positions, flickering between the 2 positions forever.
NetBeans complains about this.addKeyListener(this);. It says "Leaking this in constructor". Here is my code: (sorry in advance, first time posting)
I exported it from netbeans if anyone wants to take a look:
http://s000.tinyupload.com/?file_id=00856291054786890080
public class LeikGluggi extends javax.swing.JPanel implements ActionListener, KeyListener {
Spilari1 spilari1 = new Spilari1();//make paddle
Bolti bolti = new Bolti(); //make ball
public LeikGluggi() {
initComponents();
setSize(Leikbord.GLUGGI_BREIDD,Leikbord.GLUGGI_HAED);
this.addKeyListener(this);
this.setFocusable(true);
int i = 0;
Timer tim = new Timer(50, this);
tim.start();
}
private void uppfaera()//update
{
spilari1.uppfaera();//paddle update
bolti.uppfaera(); // ball update
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);//
g.setColor(Color.WHITE);
g.fillRect(0,0,Leikbord.GLUGGI_BREIDD,Leikbord.GLUGGI_HAED); //background
g.setColor(Color.BLUE);
spilari1.paint(g); //paddle drawn
bolti.paint(g); //ball drawn
}
#Override
public void actionPerformed(ActionEvent e)
{
uppfaera();//update called
repaint();
}
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_UP)
{
spilari1.setyHradi(-4);
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
spilari1.setyHradi(4);
}
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_UP)
{
spilari1.setyHradi(0);
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
spilari1.setyHradi(0);
}
}
public void keyTyped(KeyEvent e)
{
}
And the code for my paddle
package is.hi.vidmotsforritun.pong2.teikning;
import java.awt.Color;
import java.awt.Graphics;
public class Spilari1 {
private final int breidd = 10 ;
private final int lengd = 75;
private int y = (Leikbord.GLUGGI_HAED/2)-lengd/2;
private int yHradi = 0;
public Spilari1()
{
}
public void uppfaera()
{
y = y + yHradi;
System.out.println("HRAÐI ER "+yHradi);
}
public void paint(Graphics g)
{
g.setColor(Color.BLUE);
g.fillRect(25, y, breidd, lengd);
System.out.println("Y er "+y);
}
public void setyHradi(int hradi)
{
yHradi = hradi;
}
}
According to this Thread ("http://forums.netbeans.org/post-134877.html") the problem is that you pass a reference of this to an outside class while not fully initialized (in constructor). So you need to do this later in an initialization method

java - KeyListener fails to detect collision (platformer game)

I am making a Java game, completely free of any external libraries or engines. Everything is doing fine, but I encountered a problem with the KeyListener. I do not understand why this is happening.
Whenever I animate the Character, which is extending Object (another custom class I coded) with velX, and with custom collision detection it works fine, and the Character stops moving whenever the Character Object collides with the Block Object; i.e.
ObjectController
Character c = new Character();
Character (extends Object)
public void checkCollision(LinkedList<Object> objects){
for (int i = 0; i < objects.size(); i++) {
if(this.bounds.getRCol().intersects(objects.get(i).bounds.getLCol())){
setVelX(0);
}
}
}
Object
public void tick(LinkedList<Object> objects){
x += velX;
y += velY;
checkCollision(objects)
}
KeyListener (working version, but I want the animation to stop after key is released)
public void keyPressed(KeyEvent e){
c.setVelX(1);
}
public void keyReleased(KeyEvent e){
// nothing
}
KeyListener (this version works, the animation starts when key pressed, stops when key is released, but the collision detection doesn't work)
public void keyPressed(KeyEvent e){
c.setVelX(1);
}
public void keyReleased(KeyEvent e){
c.setVelX(0);
}
I have programmed every class correctly, or at least I feel so. The right and left collision rectangles are correctly placed on all of the Objects.
So why isn't this working? Am I doing it wrong? Or is it Swing's KeyListener's fault?
Any help would be greatly appreciated. If you need more information, please comment below and I would love to put more information!
Thanks, ProgrammersDude.
EDIT - Update 1
There is a class called Panel.class, based on JPanel It is the main container of all panels.
Then there is a Subpanel.class, which extends JPanel, too. It is an abstract class and inside of that class the tick() is called.
package com.platformer.main;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public abstract class Subpanel extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;
public boolean loaded = false;
public Thread loop = null;
public Subpanel(){
this.setFocusable(true);
this.requestFocusInWindow();
init();
loop = new Thread(this);
loop.start();
}
public void init(){
load();
loaded = true;
}
public abstract void load();
public void run(){
while(loaded){
tick();
repaint();
try{
Thread.sleep(17);
}catch(InterruptedException e){
}
}
}
public abstract void tick();
BufferedImage buffer;
Graphics bg;
public void paint(Graphics g){
buffer = (BufferedImage) this.createImage(Start.WIDTH, Start.HEIGHT);
bg = buffer.getGraphics();
paintComponent(bg);
g.drawImage(buffer, 0, 0, null);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(loaded){
render(g2);
}
}
public abstract void render(Graphics2D g);
}
}
Inside of the Gamepanel.class looks like this:
package com.platformer.subpanels;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import com.platformer.input.GameKeys;
import com.platformer.main.Start;
import com.platformer.main.Subpanel;
import com.platformer.objects.ObjectController;
public class Gamepanel extends Subpanel{
private static final long serialVersionUID = 1L;
ObjectController objectController;
GameKeys key;
public void load(){
objectController = new ObjectController();
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
objectController.character.setVelX(1);
}
public void keyReleased(KeyEvent e) {
objectController.character.setVelX(0);
}
});
}
public void tick(){
objectController.tick();
}
public void render(Graphics2D g){
g.setColor(Color.black);
g.fillRect(0, 0, Start.WIDTH, Start.HEIGHT);
objectController.render(g);
}
}
The GameKeys is the KeyListener that I was previously using. Now in the code as you see, I am using a custom KeyAdapter to test it out. It still doesn't work.
The GameKeys.class looks like this:
package com.platformer.input;
import java.awt.event.KeyEvent;
import com.platformer.objects.ObjectController;
import com.platformer.subpanels.Gamepanel;
public class GameKeys extends KeyInput{
private ObjectController objectController;
private com.platformer.objects.Character character;
public GameKeys(Gamepanel panel, ObjectController objectController){
super(panel);
this.objectController = objectController;
this.character = this.objectController.character;
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_ESCAPE:
System.exit(0);
case KeyEvent.VK_RIGHT:
character.setVelX(1);
}
}
public void keyReleased(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:
character.setVelX(0);
}
}
public void keyTyped(KeyEvent e) {
}
}
and it's based on KeyInput.class:
package com.platformer.input;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public abstract class KeyInput implements KeyListener{
public KeyInput(JPanel panel){
panel.addKeyListener(this);
}
}
I found a sort-of workaround. I added a simple boolean,
public void isCollision(){
return collision;
}
and a collision object that fits into:
for (int i = 0; i < objects.size(); i++) {
if(this.bounds.getRCol().intersects(objects.get(i).bounds.getLCol())){
collision = true;
setVelX(0);
}else{collision = false;}
}
Then this was modified from the GameKeys.class:
public void keyPressed(KeyEvent e){
if(!objectController.character.isCollision()){
objectController.character.setVelX(1);
}
}

Swing requires createBufferStrategy(2) to properly paint

I have some grids that is painted to screen one by one. I use arrow keys to move grids around as a group. Swing is said to be doubleBuffered by default so I believe frame.createBufferStrategy(2) is a bad practice but the problem is when I don't use manual double buffering, the grids are misaligned and some holes are appearing between them. Using manual double buffering fixes it.
I'm also experiencing some graphical problems(such as a dialog's buttons not displaying properly) in the actual program(not in SSCCE) so I thought it might be caused by the incorrect implementation of the double buffering.
Here is the SSCCE of the program, that causes grids to misalign when not manually double buffered:
package SSCCE;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
boolean manuallyDoubleBuffered = false; //change this
static Main main;
public final JFrame frame = new JFrame();
public final Keys keys = new Keys();
private JPanel panel;
private BufferStrategy bufferStrategy;
public static void main(String[] args) {
main = new Main();
main.initiate();
// --START LOOP--
Thread loop = new Thread(main.new Looper());
loop.start();
}
public void initiate() {
frameInit();
keys.start();
}
private void frameInit() {
frame.setSize(1200, 750);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
setUpGUI();
if (manuallyDoubleBuffered)
frame.createBufferStrategy(2); // manual double buffering
bufferStrategy = frame.getBufferStrategy();
}
private void setUpGUI() {
panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Main.main.rendering(g2d);
super.paintComponent(g);
}
};
LayoutManager layout = new FlowLayout();
frame.getContentPane().setBackground(Color.black);
panel.setLayout(layout);
panel.setOpaque(false);//
JButton but1 = new JButton("but1");
panel.add(but1);
frame.add(panel);
}
class Looper implements Runnable {
#Override
public void run() {
Main.main.gameLoop();
}
}
private void gameLoop() {
// variables are declared at start
while (true) {
if (manuallyDoubleBuffered)
paint(); // MANUAL double buffering
else
frame.repaint();// no manual double buffering
update();
try {
Thread.sleep(1000 / 60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}// loop end
private void update() {
move();
}
private void rendering(Graphics2D g2d) {
// // testing
paintGrids(g2d);
}
private void move() {
x += sx;
y += sy;
}
int sx = 0; //speedX
int sy = 0; //speedY
//top left corner of the grid
int x = 0;
int y = 0;
private void paintGrids(Graphics2D g) {
for (int i = 0; i < 100; i++) {
for (int t = 0; t < 100; t++) {
g.setColor(Color.GRAY);
g.fillRect(i * 50 + x, t * 50 + y, 50, 50);
g.setColor(Color.BLACK);
g.drawString(i + "," + t, i * 50 + x, t * 50 + y + 10);
}
}
}
public void paint() {
// uses double buffering system.
do {
do {
Graphics2D g2d = (Graphics2D) bufferStrategy.getDrawGraphics();
g2d.fillRect(0, 0, frame.getWidth(), frame.getHeight());
try {
frame.paint(g2d);
} catch (NullPointerException e) {
e.printStackTrace();
}
g2d.dispose();
} while (bufferStrategy.contentsRestored());
bufferStrategy.show();
} while (bufferStrategy.contentsLost());
}
}
class Keys implements KeyListener {// Trimmed down to shorten SSCCE
private final int leftKey = 37; // left b.
private final int rightKey = 39; // Right b.
private final int upKey = 38;// up k.
private final int downKey = 40;// down k.
public void start() {
Main.main.frame.addKeyListener(this);
Main.main.frame.setFocusable(true);
}
private void left() {
Main.main.sx -= 10;
}
private void right() {
Main.main.sx += 10;
}
private void up() {
Main.main.sy -= 10;
}
private void down() {
Main.main.sy += 10;
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println(e.getKeyCode());
switch (e.getKeyCode()) {
case leftKey:
left();
break;
case rightKey:
right();
break;
case downKey:
down();
break;
case upKey:
up();
break;
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}// END OF THE KEYS CLASS
Oracle tutorials of swing does not explain the usage with a game loop. What is the best way to do it? Am I doing anything wrong?
In case the visual error is not reproduced on other computers, I'm uploading a screenshot:
Black lines are caused by the misalinging of the rectangles. They don't exist when manual double buffering is set to true.
Thanks in advance.
Edit: I've forgot to mention that the black lines occur when grids are moving.
I' have also found out, manual double buffering drastically reduces performance.
Edit 2 : I've fixed the problem and posted it as an answer but feel free to comment on my code. Main class(except the gameLoop) is similar to the actual main class I use in my program.
I couldn't see any change in the background. Here's the code change I made.
public static void main(String[] args) {
main = new Main();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
main.initiate();
}
});
// --START LOOP--
Thread loop = new Thread(main.new Looper());
loop.start();
}
You must always start a Swing application with a call to SwingUtilities.invokeLater.
I've found the problem and writing here in case something like that ever happens to anyone else.
The problem was caused due to program being multi-threaded. Top left coordinates of the grids(x and y) were updated by the other thread in the middle of the paintGrids() method. Manual double buffering was slowing the program down (by hundreds of times) and that was allowing the paintGrids method to finish painting before x and y was updated by the keys.
To fix it I've added the following to the start of the paintGrids method:
int x = this.x;
int y = this.y;

Eclipse ADT Applet blank screen

I'm trying to show some images on my applet and have them move around but whenever I run my project through the applet all I get is a blank/black screen. I can change the color of the background, but I can't see any of my images. Also, the applet isn't initialized when I try to start the applet. Here's the code:
package test;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;
public class MCTaRE extends Applet implements Runnable, KeyListener {
private Character character;
private Image image, robot;
private Graphics graphics;
private URL base;
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Test");
robot = getImage(base, "data/character.png");
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
character = new Character();
}
#Override
public void stop() {
}
#Override
public void run() {
while (true) {
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
graphics = image.getGraphics();
}
// graphics.setColor(getBackground());
graphics.fillRect(0, 0, getWidth(), getHeight());
// graphics.setColor(getForeground());
paint(graphics);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
g.drawImage(robot, character.getInitX() - 61,
character.getInitY() - 63, this);
}
public void KeyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_SPACE:
System.out.println("Space");
break;
}
}
public void KeyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
package test;
public class Character {
private int initX = 100;
private int initY;
private int speedX = 0;
public void update(){
//if (key listener is at the top){
moveLeft();
//}
//else {
stop();
//}
initY = 200;
}
public int getInitX() {
return initX;
}
public int getInitY() {
return initY;
}
public int getSpeedX() {
return speedX;
}
public void setInitX(int initX) {
this.initX = initX;
}
public void setInitY(int initY) {
this.initY = initY;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void moveLeft(){
speedX = -5;
}
public void stop(){
speedX = 0;
}
}
Any help would be greatly appreciated I need to make this work. I can try to use an AVD but I think that would complicate things even more. And a JApplet isn't an option.
"but I can't see any of my images."
You have a few options loading the images.
I like to use getClass().getResource("/path/to/image") as it load from the class path, which is used from embedded resources.
try {
robot = ImageIO.read(getClass().getResource("/data/character.png"));
} catch (IOException ex) {
ex. printStackTrace();
}
You could do the same thing using ImageIcon.getImage where you can avoid the try/catch but I prefer the former, so you can get exception if path is incorrect
robot = new ImageIcon(getClass().getResource("/data/character.png")).getImage();
For Applet, you can use getCodeBase() as seen here
try {
URL url = new URL(getCodeBase(), "data/character.png");
robot = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
NOTE: All three options will work with your code (just tested all), given your file structure is as follows, with data in the src
ProjectRoot
src
data
character.png
test
MCTaRE.java
Side Note
You are not calling super.paint in your paint method, which will leave you with paint artifacts. So call it
#Override
public void paint(Graphics g) {
super.paint(g);
Why code an Applet in the first place. If it must be an Applet, why AWT Applet and not Swing JApplet. If this is a class assignment, have your professor read Why CS teachers should stop teaching Java applets
If you want to ditch the zero (AWT) and get with the hero (Swing), read more at Creating GUI with Swing

mouse location and graphics painting

this program is suppose to shift the two rectangles by 10 points to the right each time I click on the screen at the x coordinate 300 or greater, but it doesn't, whats the problem?
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* To change this template use File | Settings | File Templates.
*/
public class MasterMind extends JComponent implements ActionListener,MouseListener {
//private MouseEvent me;
private int screenX=0;
private int screenY=0;
private ActionEvent e;
private int xX=10;
public MasterMind() throws IOException {
}
public static void main(String [] args) throws IOException {
JFrame window = new JFrame("Master Mind");
MasterMind game= new MasterMind();
window.add(game);
window.pack();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setVisible(true);
Timer t = new Timer(30, game);
t.start();
window.addMouseListener(game);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800,600);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawRect(xX,30,200,200);
g.setColor(Color.red);
g.drawString("x,y coordinates: "+screenX+" , "+screenY,400,100);
g.setColor(Color.blue);
g.drawRect(xX+3, 33, 194, 194);
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
repaint();
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseClicked(MouseEvent e) {
MouseEvent mouseIvent = (MouseEvent) e;
int screenX = mouseIvent.getX();
int screenY = mouseIvent.getY();
System.out.println("screen(X,Y) = " + screenX + "\t" + screenY);
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
if (screenX>300) {
xX=xX+10; }
//timer animation
repaint();
}
}
I am very new to Java. so please answer in details if I may ask. thank you all.
These lines should be in the mouseClicked method rather than in actionPerformed.
if (screenX > 300) {
xX = xX + 10;
}
immediately before the existing repaint method there. They ensure that X coordinate variable xX is updated for use later in the paintComponent method.
Unrelated but make sure to invoke super.paintComponent(g) as the first statement of paintComponent
Put this ,In your MouseClicked or MousePressed or MouseReleased Method
if(me.getX()>300)
xX=xX+10;
repaint();

Categories

Resources