So I have am trying to make a keyListener for the arrow keys that responds to the arrow keys, and can handle multiple keys at once. I am trying to put the keys pressed into an ArrayList, and then handle them in my repaint() method. However, I have a problem. I am unsure where to add the keys, and where to remove them. I am not looking so much for a code solution as much as the logic that should go behind this.
//graham
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Arrows extends JPanel implements KeyListener {
private int c = 0;
private int x = 250;
private int y = 250;
private static ArrayList<Integer> keys = new ArrayList<Integer>();
public Arrows() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
}
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g) {
//*********
//need to update to make so can press (and hold) multiple different keys at once
//*********
g.setColor(Color.WHITE);
g.fillRect(x, y , 20, 20);
for(int i = 0; i < keys.size(); i++){ //********> only want to handle one at a time
//handle each key
c = keys.get(i);
switch(c){
case 37:
//left arrow
x -= 10;
keys.remove(i);
break;
case 38:
// up arrow
y -= 10;
keys.remove(i);
break;
case 39:
//right arrow
x += 10;
keys.remove(i);
break;
case 40:
//down arrow
y += 10;
keys.remove(i);
break;
}
}
g.setColor(Color.BLUE);
g.fillRect(x, y, 20, 20);
}
public void keyPressed(KeyEvent e) {
//******
//need to create a list of keys pressed, then process them in the repaint. Later delete them after pressed
//******
keys.add(e.getKeyCode());
//repaint();
}
public void keyReleased(KeyEvent e) {
//****
//here need to repaint --- need to correct to do something proper later --- due to holding down a key teleports..
//****
repaint();
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] s) {
JFrame f = new JFrame();
f.getContentPane().add(new Arrows());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
//need to null out keys
keys.add(65);
}
}
Here see if you can use my code as an example. They're fairly similar.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, g = 0;
private Color color;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 1000);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_UP) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_LEFT) {
velx = -1;
}
{
if (code == KeyEvent.VK_RIGHT) {
velx = 1;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
public static void main (String arge[]){
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Related
I am trying to get a circle to move through the input of a keyboard. I am not able to move the object at all. Can someone help me figure out what is wrong? Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class AlienInvader extends JPanel implements KeyListener{
Constants constant = new Constants();
public void update() {
constant.x += constant.xvel;
addKeyListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.MAGENTA);
g.fillOval(constant.x, constant.y, 30, 30);
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println(constant.x);
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
constant.xvel = -1;
break;
case KeyEvent.VK_RIGHT:
constant.xvel = 1;
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
constant.xvel = -1;
break;
case KeyEvent.VK_RIGHT:
constant.xvel = 1;
break;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
I am not sure what I am doing wrong. I thought it was because I wasn't calling the update method, but when I added a if statement in paintComponent (so it only calls itself once) and tried it, I had no luck.
To start with, don't call repaint within any paintXxx method. Paint methods are typically called in response to a call to repaint, therefore you are creating a nasty, never ending, ever consuming loop of resource hell.
Secondly, KeyListeners only respond to key events when 1- The component the are registered to are focusable 2- When the component they are registered to have focus.
They are a poor choice in this case. Use Key bindings instead
Thirdly, you are not providing a preferredSize hint for layout managers to use. This may or may not be a bad thing in your case, but it's possible that you component will be laid out with a size of 0x0
Example
Something like....
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MoveCircle {
public static void main(String[] args) {
new MoveCircle();
}
public MoveCircle() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int xDelta = 0;
private int keyPressCount = 0;
private Timer repaintTimer;
private int xPos = 0;
private int radius = 10;
public TestPane() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "pressed.left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "pressed.right");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "released.left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "released.right");
am.put("pressed.left", new MoveAction(-2, true));
am.put("pressed.right", new MoveAction(2, true));
am.put("released.left", new MoveAction(0, false));
am.put("released.right", new MoveAction(0, false));
repaintTimer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xPos += xDelta;
if (xPos < 0) {
xPos = 0;
} else if (xPos + radius > getWidth()) {
xPos = getWidth() - radius;
}
repaint();
}
});
repaintTimer.setInitialDelay(0);
repaintTimer.setRepeats(true);
repaintTimer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.drawOval(xPos, 0, radius, radius);
g2d.dispose();
}
public class MoveAction extends AbstractAction {
private int direction;
private boolean keyDown;
public MoveAction(int direction, boolean down) {
this.direction = direction;
keyDown = down;
}
#Override
public void actionPerformed(ActionEvent e) {
xDelta = direction;
if (keyDown) {
if (!repaintTimer.isRunning()) {
repaintTimer.start();
}
} else {
repaintTimer.stop();
}
}
}
}
}
For example...
I am trying to make a racing game which uses the arrow keys to move the car(which is a image). When I click the left arrow key I want the image to rotate a certain amount of degrees to show that the car is turning. For some reason the car isn’t turning when the left arrow key is clicked and isn’t showing any error messages either. I would appreciate any help that you can give and thanks in advance!
//GameClass:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
public class Game extends JPanel implements KeyListener {
private Image image;
BufferedImage images;
private Image image2;
private int x1, y1, velx = 0, vely = 0;
ImageIcon I2;
private Graphics2D g2;
public Game() {
x1 = 100;
y1 = 100;
}
public void paint(Graphics g) {
ImageIcon I = new ImageIcon("track.jpg");
image = I.getImage();
I2 = new ImageIcon("RedCar.png");
image2 = I2.getImage();
g.drawImage(image, 0, 0, null);
g.drawImage(image2,x1,y1,25,14,null);
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
try {
File url = new File("RedCar.png");
images = ImageIO.read(url);
}
catch(Exception r) {
r.printStackTrace();
}
Graphics g = images.getGraphics();
Graphics2D g2d = (Graphics2D)g;
g2d.rotate(Math.toRadians(15));
}
repaint();
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
x1 += 5;
velx = 1;
vely = 0;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
y1 -= 5;
velx = 0;
vely = -1;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y1 += 5;
velx = 0;
vely = 1;
}
}
#Override
public void keyReleased(KeyEvent e) {
vely = 0;
velx = 0;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//GameDemo Class:
import javax.swing.*;
public class GameDemo {
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setTitle("The Race");
frame.setSize(600, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(game);
frame.addKeyListener(game);
frame.setResizable(false);
}
}
So, I am using ImageIcon and Image to animate a character. So far my code makes it look like the character is running however for a reason that I can't figure out KeyListener is not working. I have been at this for a while and I am wondering what I am doing wrong. This is my code:
*Right now I took out moving up and down because I couldn't get side to side to work. velyY was going to be the change in y.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Image;
public class Main extends JPanel implements ActionListener,KeyListener{
ImageIcon images[];
int x = 100;
int y = 5;
int velX;
int velY;
int totalImages =3, currentImage = 0, animationDelay = 160;
Timer animationTimer;
public Main() {
images = new ImageIcon[totalImages];
images[0] = new ImageIcon("standing.png");
images[1] = new ImageIcon("ready.png");
images[2] = new ImageIcon("running.png");
startAnimation();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g2 = (Graphics) g;
if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE){
Image img = images[currentImage].getImage();
g2.drawImage(img, x, 407, null);
currentImage = (currentImage + 1) % totalImages;
}
}
public void actionPerformed(ActionEvent e) {
repaint();
x+=velX;
}
public void right(){
velX = 8;
}
public void left(){
velX = -8;
}
public void keyPressed(KeyEvent arg0) {
int code = arg0.getKeyCode();
if (code == KeyEvent.VK_A){
left();
}
if(code == KeyEvent.VK_D){
right();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
velX = 0;
velY = 0;
}
public void startAnimation() {
if (animationTimer == null) {
currentImage = 0;
animationTimer = new Timer(animationDelay, this);
animationTimer.start();
} else if (!animationTimer.isRunning())
animationTimer.restart();
}
public void stopAnimation() {
animationTimer.stop();
}
}//end class
You have to register your KeyListener to your panel, if you want it to manage key events.
The second thing is that a JPanel is not focusable by default, so you have to make it focusable to receive key events.
In your Main constructor, just add :
setFocusable(true); // make your panel focusable
addKeyListener(this); // register the key listener
I'm trying to create a program where an object continuously falls down the screen unless the user is pressing space, in which case it moves up. So far I've gotten the object to initially start falling when I run the program. When I press space, the object moves up (like it should). But, when I release the key the object stops moving. I want it to continue falling when the key is released.
I've looked at using key bindings instead of keylistener but I've had trouble with it. I am a highschool student looking to major in computer science so forgive me for not knowing too many advanced coding terms/methods. However, I am one of the best in my class and a fast learner who is eager to solve this problem. Here is my code:
public class htestnew extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 20, y = 20, vely = 1;
public htestnew() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon background = new ImageIcon("OBJECTEXAMPLE1");
background.paintIcon(this, g, 0, 0);
}
public void actionPerformed(ActionEvent e) {
if (y < 0)
{
vely = 0;
y = 0;
}
if (y > 305) //-70
{
vely = 0;
y = 305;
}
y += vely;
repaint();
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_SPACE) {
vely = -1;
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
vely = 0;
//I have tried setting this value to 1 but it does not work
}
If it is easier to use keybindings a personal and easy to follow example would be amazing. Thank you.
So, changing...
public void keyReleased(KeyEvent e) {
vely=0;
//I have tried setting this value to 1 but it does not work
}
to...
public void keyReleased(KeyEvent e) {
vely=1;
//I have tried setting this value to 1 but it does not work
}
Basically made it work (after I added in something that actually paints)
import java.awt.Dimension;
import java.awt.EventQueue;
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.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test extends JPanel implements ActionListener, KeyListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Test());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Timer t = new Timer(5, this);
int x = 20, y = 20, vely = 1;
public Test() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(x, y, 5, 5);
}
public void actionPerformed(ActionEvent e) {
if (y < 0) {
vely = 0;
y = 0;
}
if (y > 305) //-70
{
vely = 0;
y = 305;
}
y += vely;
repaint();
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_SPACE) {
vely = -1;
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
vely = 1;
//I have tried setting this value to 1 but it does not work
}
}
I would strongly recommend that you take a look at How to Use Key Bindings instead of using KeyListener, it will solve the core problem with KeyListener
Key Binding Example...
import java.awt.Dimension;
import java.awt.EventQueue;
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.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test extends JPanel implements ActionListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Test());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Timer t = new Timer(5, this);
int x = 20, y = 20, vely = 1;
public Test() {
t.start();
addKeyBinding("space.pressed", KeyEvent.VK_SPACE, true, new ChangeYAction(-1));
addKeyBinding("space.released", KeyEvent.VK_SPACE, false, new ChangeYAction(1));
}
protected void addKeyBinding(String name, int virtualKey, boolean pressed, Action action) {
addKeyBinding(name, KeyStroke.getKeyStroke(virtualKey, 0, !pressed), action);
}
protected void addKeyBinding(String name, KeyStroke keyStroke, Action action) {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(keyStroke, name);
am.put(name, action);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(x, y, 5, 5);
}
public void actionPerformed(ActionEvent e) {
if (y < 0) {
vely = 0;
y = 0;
}
if (y > 305) //-70
{
vely = 0;
y = 305;
}
y += vely;
repaint();
}
public class ChangeYAction extends AbstractAction {
private int changeYTo;
public ChangeYAction(int changeYTo) {
this.changeYTo = changeYTo;
}
#Override
public void actionPerformed(ActionEvent e) {
vely = changeYTo;
}
}
}
I am trying to create a very simple game that moves a ball up/right/left/down if you press the keys up/right/left/down. I looked up at different places, and here is what I made:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel implements KeyListener {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
static int width = (int)screenSize.getWidth();
static int height = (int)screenSize.getHeight();
static int x = width/2;
static int y = height/2;
boolean a=true;
boolean b=true;
public void keyTyped(KeyEvent e){
//nothing here
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
x=x+10;
case KeyEvent.VK_DOWN:
x=x-10;
case KeyEvent.VK_LEFT:
y=y+10;
case KeyEvent.VK_RIGHT :
y=y-10;
}
}
public void keyReleased(KeyEvent e){
//nothing here
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}
public static void main(String[] args)throws InterruptedException {
JFrame frame = new JFrame("Sample");
Game game = new Game();
frame.add(game);
frame.setSize(width,height);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.keyPressed(null);
game.repaint();
}
}
}
But how do I "run" the keyPressed program? I saw some YouTube videos that said do something like"addKeyListener" or "addActionListener", but that mean adding a text field, text box, or text area, which I don't want. This is suppose to resemble a game after all. Thanks
edited version after looking at answers:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel implements KeyListener {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
static int width = (int)screenSize.getWidth();
static int height = (int)screenSize.getHeight();
static int x = width/2;
static int y = height/2;
boolean a=true;
boolean b=true;
static Game game;
public Game(){
addKeyListener(this);
}
public void keyTyped(KeyEvent e){
//nothing here
}
#Override
public void keyReleased(KeyEvent e) {
// nothing here
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
x=x+100;
case KeyEvent.VK_DOWN:
x=x-100;
case KeyEvent.VK_LEFT:
y=y+100;
case KeyEvent.VK_RIGHT :
y=y-1000;
}
game.repaint();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}
public static void main(String[] args)throws InterruptedException {
JFrame frame = new JFrame("Sample");
game = new Game();
frame.add(game);
frame.setSize(width,height);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In your constructor , add
Game()
{
/*your code*/
addKeyListener(this);
}
You can add the keylistener to your Game object during construction.
addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
myKeyEvt(e, "keyPressed");
}
private void myKeyEvt(KeyEvent e, String text)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_KP_UP || key == KeyEvent.VK_UP)
{
//up
}
else if (key == KeyEvent.VK_KP_DOWN || key == KeyEvent.VK_DOWN)
{
//down
}
else if (key == KeyEvent.VK_KP_LEFT || key == KeyEvent.VK_LEFT)
{
//left
}
else if (key == KeyEvent.VK_KP_RIGHT|| key == KeyEvent.VK_RIGHT)
{
//right
}
}
});
Also, you will want to update your while loop to give it time to pause and refresh
while (alive)
{
update();
repaint();
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}