I am trying to develop a simple game where you can move a rectangle using the left and right arrow keys and to shoot using the spacebar.
I have added a KeyListener and others, but when I run it I have nothing as the output of key pressed or others.
I have two classes:
PaintDemo class:
package game;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PaintDemo {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Game 1.1");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setBounds(10, 10, 400, 400);
mainFrame.setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setBackground(Color.WHITE);
PaintComponent paintPanel = new PaintComponent();
mainFrame.add(mainPanel, BorderLayout.PAGE_START);
mainFrame.add(paintPanel, BorderLayout.CENTER);
mainFrame.setVisible(true);
}
}
PaintComponent class:
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
public class PaintComponent extends JPanel implements KeyListener {
int dx = 200;
int dy = 300;
int my = 300;
public Rectangle2D rec = new Rectangle2D.Double(dx , dy, 30, 10);
public PaintComponent() {
this.addKeyListener(this);
this.setBackground(Color.white);
}
public void shoot(KeyEvent evt){
if (evt.getKeyCode() == KeyEvent.VK_SPACE){
my -= 7;
repaint();
}
}
public void moveRec(KeyEvent evt){
switch(evt.getKeyCode()){
case KeyEvent.VK_LEFT:
System.out.println("test");
dx -= 2;
rec.setRect(dx, dy, 30, 10);
repaint();
case KeyEvent.VK_RIGHT:
dx += 2;
rec.setRect(dx, dy, 30, 10);
repaint();
}
}
#Override
protected void paintComponent(Graphics grphcs){
super.paintComponent(grphcs);
Graphics2D gr = (Graphics2D) grphcs;
gr.draw(rec);
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("2");
shoot(e);
}
#Override
public void keyPressed(KeyEvent e) {
moveRec(e);
}
#Override
public void keyReleased(KeyEvent e) {
}
}
The shooting method is not complete.
Change repaint() to paintComponent here and add Graphics g = getGraphics();
public void moveRec(KeyEvent evt){
switch(evt.getKeyCode()){
case KeyEvent.VK_LEFT:
System.out.println("test");
dx -= 2;
rec.setRect(dx, dy, 30, 10);
Graphics g = getGraphics();
paintComponent(g);
break;
case KeyEvent.VK_RIGHT:
dx += 2;
rec.setRect(dx, dy, 30, 10);
Graphics g = getGraphics();
paintComponent(g);
break;
}
}
Let me know if this works :)
EDIT:
Add this line
this.setFocusable(true);
to PaintComponent constructor, it will make keypresses go through.
You forgot to do two things, First one is your panel should be focusable, add this in your PaintComponent constructor this.setFocusable(true) and the second one is you have not break the switch case, so add the break statement for each case, then it should work.
switch (evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
System.out.println("test");
dx -= 2;
rec.setRect(dx, dy, 30, 10);
repaint();
break;
case KeyEvent.VK_RIGHT:
dx += 2;
rec.setRect(dx, dy, 30, 10);
repaint();
break;
}
Related
So here's my code. I implemented keyListener and actionListener. I was able to change the coordinates for the panel so It could be able to move left or right. But I have noticed that keyListener doesn't focus very well. I Have to close and rerun the app again and again for it to work and I am able to control it. I have heard of keyBidings but I don't really get it as much. How can I implement keyBindings to make the keyboard responses more focusable?
package brickBreaker;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
import javax.swing.JPanel;
public class game extends JPanel implements KeyListener, ActionListener {
private Timer timer;
private boolean play = false;
private int playerx = 650;
private int ballx=900, bally=500,ballxdir=-1,ballydir=-2;
int delay =8;
public game() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(1, 1, 1500 ,950);
// user panel
g.setColor(Color.CYAN);
g.fillRect(playerx, 900, 250, 15);
//ball
g.setColor(Color.GREEN);
g.fillOval(ballx, bally, 30, 30);
g.dispose();
}
public void right() {
play = true;
playerx += 20;
}
public void left() {
play = true;
playerx -=20;
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key ==KeyEvent.VK_LEFT) {
System.out.print("Left\n");
left();
}if (key == KeyEvent.VK_RIGHT) {
System.out.print("Right\n");
right();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
if (play) {
ballx +=ballxdir;
bally +=ballydir;
if (ballx <0) {
ballxdir =-ballxdir;
}
if (bally <0) {
ballydir =-ballydir;
}
if (ballx <1000) {
ballxdir =-ballxdir;
}
}
repaint();
}
}
Sorry for being extremely late to answer, but I think I've fixed your problem.
You're right - You need to open and close the JPanel again and again before it works. But the issue is this: The JPanel keeps losing focus. So all you have to do is add:
requestFocus(true);
to the paint() method, like so:
public void paint(Graphics g) {
requestFocus(true);
g.setColor(Color.BLACK);
g.fillRect(1, 1, 1500 ,950);
// user panel
g.setColor(Color.CYAN);
g.fillRect(playerx, 900, 250, 15);
//ball
g.setColor(Color.GREEN);
g.fillOval(ballx, bally, 30, 30);
g.dispose();
}
and the program works!
I am relatively new to java and was trying to learn how to make a program where there is this circle and I can move it around using the arrow keys. After shifting through a bunch of examples I was able to put something together. Although I am unsure how to create a KeyEvent. Any help with what I am missing would be awesome.
This is what I have so far.
import javax.swing.WindowConstants;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyEvent;
#SuppressWarnings("serial")
public class Game extends JPanel
{
int x = 0;
int y = 0;
private void moveBallUP() {
x = x + 0;
y = y + 1;
}
private void moveBallDOWN() {
x = x + 0;
y = y - 1;
}
private void moveBallLEFT() {
x = x + 1;
y = y + 0;
}
private void moveBallRIGHT() {
x = x - 1;
y = y + 0;
}
#Override
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.red);
g2d.fillOval(y, x, 50, 50);
}
public static void main(String[] args) throws InterruptedException
{
JFrame frame = new JFrame("Sample Frame");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (event.getKeyCode() == KeyEvent.VK_UP)
{
game.moveBallUP();
game.repaint();
Thread.sleep(10);
}
if (event.getKeyCode() == KeyEvent.VK_DOWN)
{
game.moveBallDOWN();
game.repaint();
Thread.sleep(10);
}
if (event.getKeyCode() == KeyEvent.VK_LEFT)
{
game.moveBallLEFT();
game.repaint();
Thread.sleep(10);
}
if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
game.moveBallRIGHT();
game.repaint();
Thread.sleep(10);
}
}
}
There are several steps to solving this: first, use a KeyListener. Add the following code to the Game class; this will represent which buttons are pressed:
private boolean upPressed=false;
private boolean downPressed=false;
private boolean leftPressed=false;
private boolean rightPressed=false;
Then, add this to the main method:
frame.addKeyListener(new KeyListener() {
#Override
public void keyReleased(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_UP:
game.upPressed=false;
break;
case KeyEvent.VK_DOWN:
game.downPressed=false;
break;
case KeyEvent.VK_LEFT:
game.leftPressed=false;
break;
case KeyEvent.VK_RIGHT:
game.rightPressed=false;
break;
}
}
#Override
public void keyTyped(KeyEvent event) {
}
#Override
public void keyPressed(KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.VK_UP:
game.upPressed=true;
break;
case KeyEvent.VK_DOWN:
game.downPressed=true;
break;
case KeyEvent.VK_LEFT:
game.leftPressed=true;
break;
case KeyEvent.VK_RIGHT:
game.rightPressed=true;
break;
}
}
});
Basically, you are setting the variables we created to true when the buttons are pressed down and false when they are released. Finally, add a Timer in the main method:
Timer timer = new Timer(10,(e)->{
if (game.upPressed)
{
game.moveBallUP();
game.repaint();
}
if (game.downPressed)
{
game.moveBallDOWN();
game.repaint();
}
if (game.leftPressed)
{
game.moveBallLEFT();
game.repaint();
}
if (game.rightPressed)
{
game.moveBallRIGHT();
game.repaint();
}
});
timer.start();
This will fire every 10 milliseconds and call your move methods if the buttons are pressed.
I have tested this and know that it works, however your move methods move the circle in the wrong directions. I assume you can fix that.
EDIT: The mistake is in this line:
g2d.fillOval(y, x, 50, 50);
Change it to:
g2d.fillOval(x,y , 50, 50);
I have this code the green square is meant to move but it doesn't I have done everything right. its just the key listen doesn't seem to be responding. I think there's a error around
addKeyListener(this); in the paintComponent in my Graphics class can you please help and tell me how to fix it and what's wrong.
my Main class
import javax.swing.JFrame;
public class Main {
static int v = 50;
static int t = 1;
public static void main(String[] args) {
JFrame frame = new JFrame("window");
frame.setVisible(true);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics object = new Graphics();
frame.add(object);
while (v > t){
object.Drawing();
}
}
}
my Graphics class
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Graphics extends JPanel implements KeyListener {
int x = 0, y= 0, xx = 100, yy = 0, ltyx = 0, ltyyxx = 0, px = 0, py = 0;
public void Drawing(){
repaint();
}
public void paintComponent (java.awt.Graphics g){
super.paintComponent (g);
addKeyListener(this);
setBackground(Color.WHITE);
g.setColor(Color.GREEN);
g.fillRect(px, py, 25, 25);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 50);
g.setColor(Color.RED);
g.fillRect(xx, yy, 50, 50);
g.drawString("times looped around screen Blue : " + ltyx , 10, 10);
g.drawString("Red : " + ltyyxx , 170, 20);
x++;
xx++;
if (x > 400){
x = 0;
y += 50;
}
if (xx > 400){
xx = 0;
yy += 50;
}
if (y > 200){
y = 0;
ltyx++;
}
if (yy > 200){
yy = 0;
ltyyxx++;
}
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:{
px++;
break;
}
case KeyEvent.VK_LEFT:{
px--;
break;
}
case KeyEvent.VK_UP:{
py++;
break;
}
case KeyEvent.VK_DOWN:{
py--;
break;
}
}
}
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:{
px = 0;
break;
}
case KeyEvent.VK_LEFT:{
px = 0;
break;
}
case KeyEvent.VK_UP:{
py = 0;
break;
}
case KeyEvent.VK_DOWN:{
py = 0;
break;
}
}
}
public void keyTyped(KeyEvent e) {
}
}
In user interfaces there is the concept of 'focus'. Only the component currently holding the focus directly receives key events. This is how for example, when typing, one text box on screen responds and not any other.
After frame.add(object);, add:
object.setFocusable(true);
object.requestFocusInWindow();
Also, the addKeyListener(this); call is in quite the wrong place. It will add another key listener every time it paints the component. It should be called only once, ideally in the constructor of the panel.
So I want to move a circle according to a certain velocity, like pong. But I'm having trouble updating the the circle's position. Here is my code that will just draw the circle and rectangle on the side.
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game extends JFrame{
public Game(){
GameScreen p1 = new GameScreen();
add(p1);
Timer t = new Timer(1000, new ReDraw());
t.start();
}
public static void main(String[] args){
Game g = new Game();
g.setLocation(400, 200);
g.setSize(700, 600);
g.setVisible(true);
}
}
class ReDraw implements ActionListener{
static int count = 0;
static int posX = 603;
static int posY = 210;
static int velX = 50;
static int velY = 50;
public void actionPerformed(ActionEvent e){
count++;
posX -= velX;
posY -= velY;
System.out.println("Flag 1: " + posX + " " + posY);
if (count == 2)
((Timer)e.getSource()).stop();
}
}
class GameScreen extends JPanel{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(654, 200, 30, 100);
g.setColor(Color.red);
g.fillOval(ReDraw.posX, ReDraw.posY, 50, 50);
}
}
I would like to use the Timer class in swing but if you have another way I would love to hear it.
EDIT: I added an attempt at updating the position of the circle.
It is necessary to repaint() the component in question, which will result in the paintComponent(Graphics) method being called again. To do that, the listener will need to have a reference to the animation panel. This is one way to do it, that includes no changes to other parts of the code.
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game001 extends JFrame {
public Game001() {
GameScreen p1 = new GameScreen();
add(p1);
Timer t = new Timer(1000, new ReDraw(p1));
t.start();
}
public static void main(String[] args) {
Game001 g = new Game001();
g.setLocation(400, 200);
g.setSize(700, 600);
g.setVisible(true);
}
}
class ReDraw implements ActionListener {
static int count = 0;
static int posX = 603;
static int posY = 210;
static int velX = 50;
static int velY = 50;
GameScreen gameScreen;
ReDraw(GameScreen gameScreen) {
this.gameScreen = gameScreen;
}
public void actionPerformed(ActionEvent e) {
count++;
posX -= velX;
posY -= velY;
System.out.println("Flag 1: " + posX + " " + posY);
gameScreen.repaint();
if (count == 4) {
((Timer) e.getSource()).stop();
}
}
}
class GameScreen extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(654, 200, 30, 100);
g.setColor(Color.red);
g.fillOval(ReDraw.posX, ReDraw.posY, 50, 50);
}
}
i have been working on mouse motion listener in Java couldn't sort it out completely because i want the object to move towards the direction where ever on the screen the mouse is pointed at but unforunately when the mouse is inside the applet window, the object moves only towards a single direction. Here is my code below..
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseOver extends Applet implements KeyListener, MouseListener,
MouseMotionListener {
private int[] Xpoints = { 0, -5, 5 };
private int[] Ypoints = { -10, -2, -2 };
private double xpos, ypos;
private Polygon poly;
int polyrot = 0;
private int width; // !! added
private int height; // !! added
public void init() {
poly = new Polygon(Xpoints, Ypoints, Xpoints.length);
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform id = new AffineTransform();
width = getSize().width;
height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.RED);
g2d.draw(poly);
g2d.translate(width / 2, height / 2);
g2d.rotate(Math.toRadians(polyrot));
g2d.scale(5, 5);
}
public void keyReleased(KeyEvent k) {
}
public void keyTyped(KeyEvent k) {
}
public void keyPressed(KeyEvent k) {
switch (k.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (polyrot < 0) {
polyrot = 359;
polyrot++;
}
repaint();
break;
case KeyEvent.VK_RIGHT:
if (polyrot > 360) {
polyrot = 0;
polyrot--;
}
repaint();
break;
}
}
public void mouseEntered(MouseEvent m) {
}
public void mouseExited(MouseEvent m) {
}
public void mouseReleased(MouseEvent m) {
}
public void mouseClicked(MouseEvent m) {
}
public void mousePressed(MouseEvent m) {
switch (m.getButton()) {
case MouseEvent.BUTTON1:
if (polyrot < 0) {
polyrot = 359;
polyrot--;
}
repaint();
break;
case MouseEvent.BUTTON2:
if (polyrot > 360) {
polyrot = 0;
polyrot++;
}
repaint();
break;
}
}
public void mouseMoved(MouseEvent e) {
xpos = getX();
if (xpos < 0) {
polyrot--;
} else if (xpos > 0) {
polyrot++;
}
repaint();
// !! break; // Doesn't belong here
}
#Override
public void mouseDragged(MouseEvent e) {
// You forgot this method
}
}
Your problem is with this line:
public void mouseMoved(MouseEvent e){
xpos=getX(); // ******
if(xpos<0){polyrot--;}
else if(xpos>0){polyrot++;}
repaint();
break;
}
That returns the x position of the applet not the mouse cursor. You need to use your MouseEvent object, e and instead get the mouse's position. Change it to:
xpos = e.getX();
Please don't ignore the comment that I made to your question. Please remember that we're volunteers who help on our free time. Please don't make it any more difficult than it has to be to help you.
I've tried to edit your code so that it compiles, and now is indented. Consider creating a Swing application, not an AWT application, since Swing apps are more flexible, powerful and robust.
This:
if (xpos < 0) {
means "if the cursor is outside of the panel".
This:
xpos = getX();
does not get a mouse coordinate.
Change your event to something like this:
public void mouseMoved(MouseEvent e) {
xpos = e.getX();
if (xpos < getWidth() / 2) {
polyrot--;
} else {
polyrot++;
}
repaint();
}
Now it rotates counter-clockwise if the cursor is on the left side of the panel and clockwise if the cursor is on the right side.
This:
g2d.draw(poly);
g2d.translate(width / 2, height / 2);
g2d.rotate(Math.toRadians(polyrot));
g2d.scale(5, 5);
will not do anything to change the image because you are doing your transforming after drawing it.
This:
Graphics2D g2d = (Graphics2D) g;
is a bad idea because you are applying transforms to the global graphics context which would carry on to subsequent repaints of other components.
Change your paint to something like this:
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g.create();
width = getSize().width;
height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height);
g2d.translate(width / 2, height / 2);
g2d.rotate(Math.toRadians(polyrot));
g2d.scale(5, 5);
g2d.setColor(Color.RED);
g2d.draw(poly);
g2d.dispose();
}
Further reading:
Painting in AWT and Swing
How to Write a Mouse Listener
There are a few things...
In your keyPressed and mousePressed events, are are only ever process the out of bounds conditions, for example...
if (polyrot < 0) {
polyrot = 359;
polyrot++;
}
//...
if (polyrot > 360) {
polyrot = 0;
polyrot--;
}
But you never process what it should do when it's within the acceptable bounds (0-359)...
Instead, you could simply add or subtract the amount from polyrot and allow the API to deal with it (surprisingly, it's capable for dealing with angles < 0 and > 359), for example...
public void mousePressed(MouseEvent m) {
switch (m.getButton()) {
case MouseEvent.BUTTON1:
polyrot--;
repaint();
break;
case MouseEvent.BUTTON2:
polyrot++;
repaint();
break;
}
}
Now, I'm not sure what you mean by "object to move towards the direction where ever on the screen the mouse is pointed". Does this mean that the object should actually change it's x/y coordinates or should it just "look" at the mouse cursor...
Based on the fact that you actually have no movement code and you basically have the object painted in a fixed location, I'm assuming "look at"...
Basically, you need to know where the mouse is and where the object is, then determine the angle between them...
public void mouseMoved(MouseEvent e) {
int x = width / 2;
int y = height / 2;
Point mousePoint = e.getPoint();
int deltaX = mousePoint.x - x;
int deltaY = mousePoint.y - y;
polyrot = -Math.atan2(deltaX, deltaY);
polyrot = Math.toDegrees(polyrot) + 180;
repaint();
}
You should note that I changed 'polyrot' to 'double'
Your paint method is also wrong. Basically, you are painting your object BEFORE you've transformed it, instead, you should be using something more like...
g2d.translate(width / 2, height / 2);
g2d.rotate(Math.toRadians(polyrot));
g2d.draw(poly);
You should also be calling super.paint(g) before you apply you own custom painting...
As a side note, you should avoid overriding paint of top level containers, like JApplet, but instead, create a custom component, extending from something like JPanel and override it's paintComponent method, performing your custom painting there (don't forget to call super.paintComponent). Take a look at Performing Custom Painting for more details
You should also avoid using KeyListener and instead use the Key Bindings API as it doesn't suffer from the same focus issues that KeyListener does...
Updated with runnable example
So I had a play around with code and produced this simple example...
Basically, I tossed out Polygon in favour of Path2D, basically because it provides much greater functionality and is easy to deal with when scaling ;)
import java.applet.Applet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
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.geom.AffineTransform;
import java.awt.geom.Path2D;
public class MouseOver extends Applet implements KeyListener, MouseListener,
MouseMotionListener {
private double xpos, ypos;
private Path2D poly;
private double polyrot = 0;
private int width; // !! added
private int height; // !! added
public void init() {
poly = new Path2D.Double();
poly.moveTo(0, 10);
poly.lineTo(5, 0);
poly.lineTo(10, 10);
poly.lineTo(0, 10);
poly.closePath();
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g) {
super.paint(g);;
Graphics2D g2d = (Graphics2D) g;
AffineTransform id = new AffineTransform();
width = getSize().width;
height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height);
g2d.setColor(Color.RED);
id.scale(5, 5);
Shape scaled = poly.createTransformedShape(id);
Rectangle bounds = scaled.getBounds();
g2d.translate((width - bounds.width) / 2, (height - bounds.height) / 2);
g2d.rotate(Math.toRadians(polyrot), bounds.width / 2, bounds.height / 2);
g2d.setStroke(new BasicStroke(5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2d.draw(scaled);
}
public void keyReleased(KeyEvent k) {
}
public void keyTyped(KeyEvent k) {
}
public void keyPressed(KeyEvent k) {
switch (k.getKeyCode()) {
case KeyEvent.VK_LEFT:
polyrot++;
repaint();
break;
case KeyEvent.VK_RIGHT:
polyrot--;
repaint();
break;
}
}
public void mouseEntered(MouseEvent m) {
}
public void mouseExited(MouseEvent m) {
}
public void mouseReleased(MouseEvent m) {
}
public void mouseClicked(MouseEvent m) {
}
public void mousePressed(MouseEvent m) {
switch (m.getButton()) {
case MouseEvent.BUTTON1:
polyrot--;
repaint();
break;
case MouseEvent.BUTTON2:
polyrot++;
repaint();
break;
}
}
public void mouseMoved(MouseEvent e) {
int x = width / 2;
int y = height / 2;
Point mousePoint = e.getPoint();
int deltaX = mousePoint.x - x;
int deltaY = mousePoint.y - y;
polyrot = -Math.atan2(deltaX, deltaY);
polyrot = Math.toDegrees(polyrot) + 180;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
// You forgot this method
}
}
From here:
public void mouseMoved(MouseEvent e){
xpos=getX();
if(xpos<0){polyrot--;}
else if(xpos>0){polyrot++;}
repaint();
break;
}
It seems you update only the xpos. You should update also the variable ypos.
You might want to do it with something like this:
ypos=e.getY();
if (this.ypos<0){
this.polyrot--;
}else if (this.ypos>0) {
this.polyrot++;
}
this.repaint();