I've been experimenting with creating a java game but I've hit a roadblock, I can't get java to listen to any of my keys even when I'm just using print statements to test it out. From what I understand I've implemented KeyListener correctly and added the key listener to the Applet but it still isn't working.
My main class:
import java.awt.*;
import javax.swing.*;
public class Container extends JApplet implements Runnable {
private static final long serialVersionUID = 1L;
public static Dimension size = new Dimension(720,560); //Size of Screen
private static final int PIXELSIZE = 2;
public static Dimension pixel = new Dimension(size.width/PIXELSIZE,
size.height/PIXELSIZE); // Dimesions of screen in terms of pixels
public static final String NAME = "Game";
public static boolean isRunning = false;
private Image screen;
public static Level level;
public static MainCharacter p1;
public Container(){
setPreferredSize(size);
addKeyListener(p1);
}
public void start(){
new Tile();
level = new Level();
p1 = new MainCharacter(20,40);
isRunning = true;
new Thread(this).start();
}
public void tick(){
p1.tick();
}
public void render(){
Graphics g = screen.getGraphics();
g.setColor(new Color(130,160,255));
g.fillRect(0, 0, pixel.width, pixel.height);
level.render(g);
p1.render(g);
g = getGraphics();
g.drawImage(screen, 0, 0, size.width, size.height,
0, 0, pixel.width, pixel.height, null);
g.dispose();
}
public void run() {
screen = createVolatileImage(pixel.width,pixel.height);
while(isRunning){
tick();
render();
try{
Thread.sleep(5);
}catch(InterruptedException e){}
}
}
public static void main(String[] args){
Container container = new Container();
JFrame frame = new JFrame();
frame.add(container);
frame.pack();
frame.setTitle(NAME);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
container.start();
}
public static void right(){
p1.right();
}
public static void left(){
p1.left();
}
}
My character class:
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class MainCharacter extends Tall implements KeyListener{
public double fallSpeed = 1.5;
public double moveSpeed = 1.0;
public double xSpeed = 1;
public MainCharacter(int width, int height){
setBounds(Container.pixel.width/2 - width/2,
Container.pixel.height/2 - height/2,
width, height);
}
public void tick(){
if(Container.level.space[(int)(x+width)][(int)(y+height)] &&
Container.level.space[(int)(x)][(int)(y+height)] &&
Container.level.space[(int)(x+width)][(int)(y)] &&
Container.level.space[(int)(x)][(int)(y)])
y += fallingSpeed;
}
public void render(Graphics g){
g.drawImage(Tile.tileset_terrain, (int)x, (int)y,
(int)(x+width),(int)(y+height),
Tile.CHARACTER[0]*Tile.TILE_SIZE,
Tile.CHARACTER[1]*Tile.TILE_SIZE,
Tile.CHARACTER[0]*Tile.TILE_SIZE +(int)width,
Tile.CHARACTER[1]*Tile.TILE_SIZE + (int)height, null);
}
public void right(){
x += xSpeed;
}
public void left(){
x -= xSpeed;
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("hey");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("hey");
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("hey");
}
}
It looks like p1 is null when you add it as a KeyListener.
You add it as a KeyListener here:
public Container(){
setPreferredSize(size);
System.out.println(p1); // try this...
addKeyListener(p1);
}
But instantiate it here:
public void start(){
new Tile();
level = new Level();
p1 = new MainCharacter(20,40);
isRunning = true;
new Thread(this).start();
}
KeyListeners are fickle. They require that the component they are registered to are not only focusable, but have keyboard focus.
It's recommend that instead, you should use Key Bindings instead
Related
I need to draw in AWT/Swing rectangles that are moving from frame to frame.
I have a Playground class
public Playground(int sizeX, int sizeY)
{
frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setSize(sizeX, sizeY);
panel.setDoubleBuffered(true);
panel.setVisible(true);
frame.add(panel);
frame.pack();
frame.setSize(sizeX, sizeY);
}
public void refresh()
{
panel.repaint();
}
public Graphics getGraphics()
{
return panel.getGraphics();
}
This is the class in which objects should be drawn:
public class Star {
private static int size = 10;
private int posX;
private int posY;
public Star(int posX, int posY)
{
this.posX = posX;
this.posY = posY;
}
public void paint(Graphics g)
{
g.fillRect(posX, posY, size, size);
}
public int getPosX() {
return posX;
}
public int getPosY() {
return posY;
}
}
This is the main method:
public static void main(String[] args) {
Playground playground = new Playground(400, 400);
Star star = new Star(100, 100);
Star star2 = new Star(125, 125);
while(1 == 1)
{
playground.refresh();
star.paint(playground.getGraphics());
star2.paint(playground.getGraphics());
}
}
The objects are drawn but are flickering, how can I stop it from flickering?
Edit: I solved the flickering for one element, by changing the refresh method to:
public void refresh()
{
panel.getGraphics().clearRect(0,0, panel.getWidth(), panel.getHeight());
}
Unfortunately only one Element is not flickering all others are still flickering.
The following is a one-file mcve that demonstrates moving (rotating for simplicity) a rectangle by custom painting.
One-file meaning that you can copy-paste the entire code into one file (AnimateRectangle.java) and execute it.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AnimateRectangle {
private JFrame frame;
public AnimateRectangle(Model model){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new MyJPanel(model);
panel.setDoubleBuffered(true);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
void refresh() {
frame.repaint();
}
public static void main(String[] args) throws InterruptedException {
Controller controller = new Controller(400, 400);
while (true) {
Thread.sleep(1000);
SwingUtilities.invokeLater(()->controller.animate());
}
}
}
//"wires" gui and model
class Controller{
private Model model;
private AnimateRectangle view;
Controller(int sizeX, int sizeY){
model = new Model(sizeX, sizeY);
view = new AnimateRectangle(model);
}
void animate() {
int newAngle = (model.getAngle() < 360 ) ? model.getAngle()+1 : 0 ;
model.setAngle(newAngle);
view.refresh();
}
}
//represents the inforamtion the GUI needs
class Model{
int sizeX, sizeY, angle = 0;
public Model(int sizeX, int sizeY) {
this.sizeX = sizeX;
this.sizeY = sizeY;
}
int getSizeX() { return sizeX; }
int getSizeY() {return sizeY;}
int getAngle() {return angle;}
//degrees
void setAngle(int angle) { this.angle = angle; }
}
//a JPanel with custom paint component
class MyJPanel extends JPanel {
private Model model;
public MyJPanel(Model model) {
this.model = model;
setPreferredSize(new Dimension(model.getSizeX(), model.getSizeY()));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
int sizeX = model.getSizeX(), sizeY = model.getSizeY();
g2d.rotate(Math.toRadians(model.getAngle()), sizeX /2, sizeY/2);
g2d.fillRect(sizeX/4, sizeY/4, sizeX/2, sizeY/2);
}
}
A better option (see camickr comment) is to animate using swing Timer. To do so, remove animate() method, and replace it with :
void animateWithTimer(){
new Timer(1000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int newAngle = (model.getAngle() < 360 ) ? model.getAngle()+1 : 0 ;
model.setAngle(newAngle);
view.refresh();
}
}).start();
}
and change main to use it :
public static void main(String[] args) throws InterruptedException {
Controller controller = new Controller(400, 400);
controller.animateWithTimer();
}
What I'm trying to do
Making a Pong game where the Y axis gets the value from my cursor according to the application
What did I tried
private void pallet() {
ycur=(int)MouseInfo.getPointerInfo().getLocation().getY();
}
This way I get the Y value according to my monitor instead of the application.
I also tried to use the MouseEvent.getY(), but I get the error when trying to call this method from the main.
private void pallet() {
ycur=(int)MouseInfo.getPointerInfo().getLocation().getY();
}
This is how my code looks like, I think the problem lies in how I'm using my main and methods but I'm not sure.
public class MyFirst extends JPanel {
public int x = 500, y = 300, border = 30;
public boolean goingDown = true;
public int ycur, cursor;
public void moveBall() {
x++;
if (goingDown == true) {
y++;
} else if (goingDown == false) {
y--;
}
if (y == getHeight() - border) {
goingDown = false;
} else if (y == 0) {
goingDown = true;
}
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.fillOval(x, y, 30, 30);
g.fillRect(30, ycur, 15, 100);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Pong");
frame.pack();
frame.setSize(1000, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
MyFirst game = new MyFirst();
frame.add(game);
while (true) {
game.pallet(e);
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
public void pallet(MouseEvent e) {
ycur=e.getY();
}
}
Problems with your code:
As already mentioned, you're fighting against Swing's event-driven architecture. Instead of a while true loop, use listeners, including a MouseMotionListener ot track the changes in the mouse location, and an ActionListener tied to a Swing Timer to move the ball.
Avoid using Thread.sleep(...) in Swing GUI's except with great care as this can put the entire application to sleep.
Avoid putting too much logic within the main method. This method should be short, should create the key objects, connect them, set the program in motion and that's it.
Paint with the paintComponent method, not the paint method. It results in smoother animation with its double buffering.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MoveBallTest extends JPanel{
private static final int PREF_W = 1000;
private static final int PREF_H = 600;
private static final int TIMER_DELAY = 12;
private static final int SPRITE_WIDTH = 30;
private static final Color OVAL_SPRITE_COLOR = Color.RED;
private static final Color RECT_SPRITE_COLOR = Color.BLUE;
private static final int DELTAY_Y = 1;
private boolean goingDown = true;
private Timer timer = new Timer(TIMER_DELAY, this::timerActionPerformed);
private int ovalSpriteY;
private int rectSpriteY;
public MoveBallTest() {
timer.start();
MyMouse myMouse = new MyMouse();
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(OVAL_SPRITE_COLOR);
g.fillOval(SPRITE_WIDTH, ovalSpriteY, SPRITE_WIDTH, SPRITE_WIDTH);
g.setColor(RECT_SPRITE_COLOR);
g.fillRect(SPRITE_WIDTH, rectSpriteY, SPRITE_WIDTH / 2, SPRITE_WIDTH * 3);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
public void timerActionPerformed(ActionEvent e) {
if (ovalSpriteY <= 0) {
goingDown = true;
} else if (ovalSpriteY >= getHeight() - SPRITE_WIDTH) {
goingDown = false;
}
ovalSpriteY += goingDown ? DELTAY_Y : -DELTAY_Y;
repaint();
}
private class MyMouse extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
rectSpriteY = e.getY();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MoveBallTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MoveBallTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I am writing a Crazy Eights game and trying to have mouse control added in. I just starting writing it but I can't verify if it's working or not. I've added System.out.println() to the pressed and released event calls but no output happens. I just need to get it working and be able to see an output of some kind for debugging. I've also tried to use another example on stackoverflow to help me out but I'm still having issues. The below code is what I'm working with. Let me know if you need to see another class.
Thanks
MouseControl.java
package crazyeightscountdown.CoreClasses;
import java.awt.Canvas;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseControl extends MouseAdapter {
public Canvas canvas;
public MouseControl (Canvas c){
this.canvas = c;
}
#Override
public void mouseReleased (MouseEvent e){
System.out.println("Mouse Released.\n");
}
#Override
public void mousePressed (MouseEvent e){
System.out.println("Mouse Pressed.\n");
}
#Override
public void mouseClicked (MouseEvent e){
}
#Override
public void mouseEntered (MouseEvent e){
}
#Override
public void mouseExited (MouseEvent e){
}
}//class
Game.java
package crazyeightscountdown;
import static com.sun.java.accessibility.util.AWTEventMonitor.addMouseListener;
import static crazyeightscountdown.CoreClasses.Constants.CARDPICX;
import crazyeightscountdown.CoreClasses.Deck;
import crazyeightscountdown.CoreClasses.MouseControl;
import crazyeightscountdown.CoreClasses.Player;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
//Sets up parameters for the game window
public class Game implements Runnable {
private Display display;
public int width, height;
public Game(String title, int width, int height) {
this.width = width;
this.height = height;
display = new Display(title, width, height);
StartGame();
}
//create the game decks
//Deck maindeck = new Deck();
public Deck faceupdeck = new Deck();
public Deck facedowndeck = new Deck();
Deck tempdeck = new Deck();
public int deckindex = 0;
public Player playerone = new Player();
public Player playertwo = new Player();
private BufferStrategy bs;
private Graphics g;
private boolean running = false;
private Thread thread;
public void StartGame() {
//setup mouse
addMouseListener (new MouseControl(display.getCanvas()));
//set players
playerone.SetPlayer(1);
playertwo.SetPlayer(2);
//set values to main deck
facedowndeck = facedowndeck.SetDeck(facedowndeck);
//shuffle the deck
facedowndeck = facedowndeck.ShuffleDeck(facedowndeck);
//hand out first deal
FirstDeal();
}
public void FirstDeal() {
int playerindex = 1;
deckindex = 1;
//deal each player 8 cards to start
for (int h = 0; h < 8; h++) {
playerone.hand.card[playerindex] = facedowndeck.card[deckindex];
facedowndeck.card[deckindex].present = false;
playerone.hand.card[playerindex].present = true;
deckindex++;
playertwo.hand.card[playerindex] = facedowndeck.card[deckindex];
facedowndeck.card[deckindex].present = false;
playerone.hand.card[playerindex].present = true;
deckindex++;
playerindex++;
//facedowndeck.Truncate(facedowndeck);
}
//put card face up
faceupdeck.card[1] = facedowndeck.card[deckindex];
deckindex++;
}
private void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Clear Screen
g.clearRect(0, 0, width, height);
/******* START DRAWING HERE **********/
//draw player1 deck
for (int f = 1; f < 9; f++) {
g.drawImage(playerone.hand.card[f].pic, (CARDPICX * (f - 1)) + (f * 5), 5, null);
g.drawImage(playertwo.hand.card[f].pic, (CARDPICX * (f - 1)) + (f * 5), 450, null);
}
g.drawImage(faceupdeck.card[1].pic,400, 200, null);
/*********** END DRAWING HERE ***********/
bs.show();
g.dispose();
}
private void tick() {
}
public void run() {
//init();
while (running) {
tick();
render();
}
stop();
}
public synchronized void start() {
if (running) {
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
if (!running) {
return;
}
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}//class
Display.java
package crazyeightscountdown;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
//display parameters for the window
public class Display {
public JFrame frame;
public Canvas canvas;
public String title;
public int width, height;
public Display(String title, int width, int height){
this.title = title;
this.width = width;
this.height = height;
createDisplay();
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
frame.add(canvas);
frame.pack();
}
public Canvas getCanvas(){
return canvas;
}
}
You have to add the MouseListener to a component: frame.addMouseListener(...)
I am making a sort of pong game, but I have a problem.
I have a method in my code, that checks if the user input is a key pressed.
But it won't execute when I press(In my case) the UP key.
This is the code, sorry for bad English, please help me:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements ActionListener,KeyListener{
Player player = new Player();
Ball ball = new Ball();
public GamePanel(){
Timer time = new Timer(50, this);
time.start();
}
private void update(){
player.update();
ball.update();
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 600);
player.paint(g);
ball.paint(g);
}
public void actionPerformed(ActionEvent e){
update();
repaint();
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP)
{
player.setyv(-5);
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
Again,
Use Key Bindings and not a KeyListener since this can help you take focus out of the picture without use of kludges.
Always be sure to call the super's paintComponent method within your override.
For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements ActionListener {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
Player player = new Player();
Ball ball = new Ball();
public GamePanel() {
Timer time = new Timer(50, this);
time.start();
// !! set key bindings
int condition = WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition);
ActionMap actionMap = getActionMap();
KeyStroke up = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
inputMap.put(up, up.toString());
actionMap.put(up.toString(), new AbstractAction() {
#Override
public void actionPerformed(ActionEvent evt) {
player.setyv(-5);
}
});
KeyStroke down = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
inputMap.put(down, down.toString());
actionMap.put(down.toString(), new AbstractAction() {
#Override
public void actionPerformed(ActionEvent evt) {
player.setyv(5);
}
});
}
private void update() {
player.update();
ball.update();
}
// !! public void paintComponent(Graphics g) {
protected void paintComponent(Graphics g) {
super.paintComponent(g); // !!
g.setColor(Color.BLACK);
g.fillRect(0, 0, PREF_W, PREF_H); // !!
player.paint(g);
ball.paint(g);
}
// !!
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
// !!
private static void createAndShowGui() {
GamePanel mainPanel = new GamePanel();
JFrame frame = new JFrame("GamePanel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
interface Playable {
void update();
void paint(Graphics g);
}
class Player implements Playable {
private static final Color PLAYER_COLOR = Color.RED;
private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, 24);
private int x = 400;
private int y = 400;
private int yv = 0;
private int xv = 0;
#Override
public void update() {
y += yv;
x += xv;
}
public void setyv(int i) {
yv += i;
}
#Override
public void paint(Graphics g) {
g.setFont(FONT);
g.setColor(PLAYER_COLOR);
g.drawString("P", x, y);
}
}
class Ball implements Playable {
#Override
public void update() {
// TODO Auto-generated method stub
}
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
}
}
This is my code so far, what I want to do is to add a new Object every time the mouse is moved, but the system is not even accessing the MouseEvent class after hours of thinking, I still am not able to figure the problem. Please Help!!
My main class:
package testing;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
public class Wincall extends Canvas implements Runnable {
public static final int HEIGHT = 640, WIDTH = 1080;
private WinTest w;
private Handler handler;
private ME me = new ME(this);
public Wincall(){
handler = new Handler();
w = new WinTest(WIDTH, HEIGHT, "Test", this);
}
public synchronized void run(){
while(true){
long now = System.currentTimeMillis();
this.tick();
this.render();
long after = System.currentTimeMillis();
int tt = (int) (after-now);
if(tt>5)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Time Taken in millisecs : " + tt);
}
}
public void tick(){
handler.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//render
g.setColor(Color.BLACK);
g.fillRect(0 ,0 ,WIDTH, HEIGHT);
handler.render(g);
//render end
g.dispose();
bs.show();
}
public void addStuff(){
handler.addObject(new TestGO(me.getX(), me.getY(), 32, 32));
}
public static void main(String[] args){
new Wincall();
}
}
My MouseEvent class:
package testing;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class ME implements MouseMotionListener{
private int mx = 0, my = 0;
private Wincall game;
public ME(Wincall game){
this.game = game;
}
public void mouseDragged(MouseEvent e){}
public void mouseMoved(MouseEvent e) {
game.addStuff();
mx = e.getX();
my = e.getY();
System.out.println(mx);
System.out.println(my);
}
public int getX(){
return mx;
}
public int getY(){
return my;
}
}
My window class:
package testing;
import java.awt.Canvas;
import javax.swing.JFrame;
public class WinTest {
private static final long serialVersionUID = -369751247370351003L;
public WinTest(int h, int w, String title, Wincall game){
JFrame f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(h, w);
f.add(game);
f.setVisible(true);
f.requestFocus();
f.setResizable(false);
f.setFocusable(true);
game.addMouseMotionListener(new ME());
game.run();
}
}
Though its not clear what you are trying to do. But you need to add the MouseMotionListener to canvas not to the JFrame. Since you are adding canvas to the JFrame, it is the canvas which should capture MouseEvents. Hence, your Wintest should probably look like this :
public class WinTest extends Canvas {
private static final long serialVersionUID = -369751247370351003L;
public WinTest(int h, int w, String title, Wincall game, ME me) {
JFrame f = new JFrame(title);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(h, w);
f.add(game);
f.setVisible(true);
f.requestFocus();
f.setResizable(false);
f.setFocusable(true);
// f.addMouseMotionListener(me);
game.addMouseMotionListener(me);
game.run();
}
}
Update :
Wincalll Class:
public class Wincall extends Canvas implements Runnable {
public static final int HEIGHT = 640, WIDTH = 1080;
private WinTest w;
// private Handler handler;
private ME me = new ME(this);
public Wincall() {
// handler = new Handler();
w = new WinTest(WIDTH, HEIGHT, "Test", this, me);
}
public synchronized void run() {
while (true) {
long now = System.currentTimeMillis();
this.tick();
this.render();
long after = System.currentTimeMillis();
int tt = (int) (after - now);
if (tt > 5)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println("Time Taken in millisecs : " + tt);
}
}
public void tick() {
// handler.tick();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// render
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
// handler.render(g);
// render end
g.dispose();
bs.show();
}
public void addStuff() {
System.out.println("addStuff");
// handler.addObject(new TestGO(me.getX(), me.getY(), 32, 32));
}
public static void main(String[] args) {
new Wincall();
}
}
I was looking at some of my old source codes:
Try
addMouseMotionListener(me);
Instead of:
f.addMouseMotionListener(me);