I have been following some java game development tutorial , and I was able to create an oval shaped object that can move with my keyboard input and created boundaries , however I attempted to replace the oval with an image but for some reason it is not showing up, I'm pretty sure the image I chose is not large , it is more like a small icon and thanks in advance.
package javagame;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class JavaGame extends JFrame{
int x,y;
private Graphics dbg;
private Image dbImage;
Font font = new Font("Arial" , Font.BOLD, 30);
Image face;
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int KeyCode = e.getKeyCode();
if(KeyCode == e.VK_LEFT) {
if(x<=0)
x=0;
else
x -=15;
}
if(KeyCode == e.VK_DOWN) {
if(y>=480)
y=480;
else
y+=5;
}
if(KeyCode == e.VK_UP) {
if(y<=20)
y=20;
else
y-=5;
}
if(KeyCode == e.VK_RIGHT) {
if(x>=480)
x=480;
else
x+=5;
}
}
public void keyReleased(KeyEvent e){
}
}
public JavaGame() {
//game images
ImageIcon i = new ImageIcon("C:/Users/Sheref/Documents/NetBeansProjects/avaGame/src/javagame/type-of-solder-001-512.gif");
face = i.getImage();
//game properties
addKeyListener(new AL());
setTitle(" Strategy Game");
setSize(500,500);
setResizable(true);
setVisible(true);
setBackground(Color.CYAN);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 20 ;
y = 30;
}
public void paint(Graphics g){
dbImage = createImage(getWidth() , getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage , 0 , 0 , this);
}
public void paintComponent(Graphics g)
{
g.setFont(font);
g.drawImage(face, x, y, this);
repaint();
}
public static void main(String[] args) {
new JavaGame();
}
}
In your paint method, instead of
this.dbImage = this.createImage(this.getWidth(), this.getHeight());
put:
this.dbImage = this.createImage((int) this.getSize().getWidth(), (int) this.getSize().getHeight());
Related
I'm trying to draw over a vlcj (java binding of the VLC library) panel so that I can play a video and draw over it. And I have encounter some issues. Here is the full base code:
Code-listing 1: AppOverlay.java
package app;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.jna.platform.WindowUtils;
#SuppressWarnings("serial")
public class AppOverlay extends Window implements Runnable {
private final boolean isRunning;
private final int fps;
private BufferedImage graphics;
private BufferedImage img;
private int x, y;
private boolean ltr;
public AppOverlay(Window owner) {
super(owner, WindowUtils.getAlphaCompatibleGraphicsConfiguration());
setBackground(new Color(0,0,0,0));
graphics = new BufferedImage(1280,800, BufferedImage.TYPE_INT_ARGB);
isRunning = true;
img = null;
ltr = true;
fps = 60;
x = 0;
y = 0;
}
#Override
public void run(){
while(isRunning){
try{
Thread.sleep(1000/fps);
} catch(InterruptedException e){
e.printStackTrace();
}
if(ltr) {
if(x < 1280) x++;
else ltr = false;
} else {
if(x < 0) ltr = true;
else x--;
}
repaint();
}
}
public void createAndShowGUI() {
setVisible(true);
Thread thread = new Thread(this);
thread.start();
String path = "Drive:\\path\\to\\image.png";
try {
img = ImageIO.read(new java.io.FileInputStream(path));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
Graphics2D gfx = graphics.createGraphics();
gfx.setColor(new Color(255,255,255,0));
gfx.clearRect(0, 0, 1280, 800);
if(img != null) gfx.drawImage(img, x, y, null);
gfx.dispose();
g2d.drawImage(graphics, 0, 0, null);
}
}
Code-listing 2: AppPlayer.java
package app;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
#SuppressWarnings("serial")
public class AppPlayer extends EmbeddedMediaPlayerComponent {
}
Code-listing 3: AppFrame.java
package app;
import java.awt.Dimension;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class AppFrame extends JFrame {
private AppPlayer appPlayer;
private AppOverlay overlay;
public AppFrame(){
super();
}
public void createAndShowGUI() {
appPlayer = new AppPlayer();
appPlayer.setPreferredSize(new Dimension(1280,800));
getContentPane().add(appPlayer);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("App");
setVisible(true);
pack();
overlay = new AppOverlay(this);
appPlayer.mediaPlayer().overlay().set(overlay);
appPlayer.mediaPlayer().overlay().enable(true);
overlay.createAndShowGUI();
}
}
Code-listing 4: Main.java
package main;
import javax.swing.SwingUtilities;
import app.AppFrame;
public class Main {
public static void main(String[] args) {
final AppFrame app = new AppFrame();
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
app.createAndShowGUI();
}
});
}
}
with that and the vlcj-4 library you should be able to test my code yourself. My issue is that the Overlay (AppOverlay class that extends the Window class) doesn't display or refresh the animation unless I deselect the window (I click on another window or on the desktop or the OS toolbar) so that the window (application) is inactive then select the window (the application) again. It will only load one frame and that's it. I have to deselect and reselect the window again for it to load another frame (this is only the case for the Overlay i.e. if I play a video in the AppPlayer class the video will be playing just fine.
What I want is to be able to draw some animated graphics on the overlay. I know that with the JPanel class there is the paintComponent() method but the Window class doesn't have that method (only the paint() and repaint() methods are available).
What should I do to fix this?
EDIT:
I tried adding a JPanel on which I draw instead of drawing directly on the AppOverlay
Code-listing 5: AppPanel.java
package app;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class AppPanel extends JPanel implements Runnable {
private int x, y;
private boolean ltr;
public AppPanel() {
x = 0;
y = 0;
ltr = true;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(0,0,0,0));
g.clearRect(0, 0, 1280, 800);
g.setColor(Color.RED);
g.fillRect(x, y, 100, 100);
}
#Override
public void run() {
while(true){
try{
Thread.sleep(1000/60);
} catch(InterruptedException e){
e.printStackTrace();
}
if(ltr) {
if(x < 1280) x++;
else ltr = false;
} else {
if(x < 0) ltr = true;
else x--;
}
repaint();
}
}
}
then adding it to the AppOverlay.
Code-listing 6: AppOverlay.java with partial modification
public class AppOverlay extends Window implements Runnable {
//previous field declaration above ...
AppPanel panel;
AppPlayer player = null;
public AppOverlay(Window owner) {
//previous constructor instructions above...
panel = new AppPanel();
add(panel);
}
public void createAndShowGUI(AppPlayer player) {
setVisible(true);
/*
Thread thread = new Thread(this);
thread.start();
String path = "Drive:\\path\\to\\image.png";
try {
img = ImageIO.read(new java.io.FileInputStream(path));
} catch (IOException e) {
e.printStackTrace();
}
*/
Thread panelThread = new Thread(panel);
panelThread.start();
}
}
Doing this will display the graphics of the JPanel and animate them as needed.
If you know a way to make the JPanel background transparent (so that we can see through it) while still letting it display its graphics. That would solve the issue for sure.
I played around a bit with your example and came up with something working, but I wouldn't call it a nice solution.
The main issue seems to be that there is no way to tell the overlay to refresh (or I just have not found it). Just repainting the overlay does not update it on screen, so the workaround I used is to hide and show it again.
For the timeing of the update interval I used a javax.swing.Timer.
(In a real version you probably want to start and stop the timer via the MediaPlayerEventListener).
As a side effect the repaint method is called and the x coordinate is adjusted to move the image around the screen.
In the simplified example below (use your main to run it), I moved a red rectangle with the x coordinate instead of some unknown image.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import com.sun.jna.platform.WindowUtils;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.OverlayApi;
public class AppFrame extends JFrame {
private static final long serialVersionUID = -1569823648323129877L;
public class Overlay extends Window {
private static final long serialVersionUID = 8337750467830040964L;
private int x, y;
private boolean ltr = true;
public Overlay(Window owner) throws HeadlessException {
super(owner, WindowUtils.getAlphaCompatibleGraphicsConfiguration());
setBackground(new Color(0,0,0,0));
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (ltr) {
if (x < 1180)
x += 1;
else
ltr = false;
} else {
if (x < 0)
ltr = true;
else
x -= 1;
}
g.setColor(Color.RED);
g.fillRect(x, y, 100, 100);
String s = Integer.toString(x);
g.setColor(Color.WHITE);
g.drawChars(s.toCharArray(), 0, s.length(), x+10, y+50);
}
}
private EmbeddedMediaPlayerComponent appPlayer;
public void createAndShowGUI() {
appPlayer = new EmbeddedMediaPlayerComponent();
appPlayer.setPreferredSize(new Dimension(1280, 800));
getContentPane().add(appPlayer);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("App");
setVisible(true);
pack();
Overlay overlay = new Overlay(this);
OverlayApi api = appPlayer.mediaPlayer().overlay();
api.set(overlay);
api.enable(true);
//appPlayer.mediaPlayer().media().play(" ... ");
Timer timer = new Timer(0, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
api.enable(false);
api.enable(true);
}
});
timer.setRepeats(true);
timer.setDelay(200);
timer.start();
}
}
If that is an option for you, it might be far easier to use an animated gif instead. At least that is working on its own (no need for the Timer).
Update:
As you figured out using a JPanel seems to work better.
Just use setOpaque(false) to make it transparent.
Here an adjusted example.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.OverlayApi;
public class AppFrame2 extends JFrame {
private static final long serialVersionUID = -1569823648323129877L;
public class OverlayPanel extends JPanel {
private static final long serialVersionUID = 8070414617530302145L;
private int x, y;
private boolean ltr = true;
public OverlayPanel() {
this.setOpaque(false);
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (ltr) {
if (x < 1180)
x += 1;
else
ltr = false;
} else {
if (x < 0)
ltr = true;
else
x -= 1;
}
g.setColor(Color.RED);
g.fillRect(x, y, 100, 100);
String s = Integer.toString(x);
g.setColor(Color.WHITE);
g.drawChars(s.toCharArray(), 0, s.length(), x+10, y+50);
}
}
public class Overlay extends Window {
private static final long serialVersionUID = 8337750467830040964L;
OverlayPanel panel;
public Overlay(Window owner) throws HeadlessException {
super(owner);
setBackground(new Color(0,0,0,0));
panel = new OverlayPanel();
this.add(panel);
}
}
private EmbeddedMediaPlayerComponent appPlayer;
public void createAndShowGUI() {
appPlayer = new EmbeddedMediaPlayerComponent();
appPlayer.setPreferredSize(new Dimension(1280, 800));
getContentPane().add(appPlayer);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("App");
setVisible(true);
pack();
Overlay overlay = new Overlay(this);
OverlayApi api = appPlayer.mediaPlayer().overlay();
api.set(overlay);
api.enable(true);
//appPlayer.mediaPlayer().media().play(" ... ");
Timer timer = new Timer(0, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
overlay.panel.repaint();
}
});
timer.setRepeats(true);
timer.setDelay(17);
timer.start();
}
}
You have already done the bulk of the work. Simply repaint the frame every time you draw over it by calling app.repaint();
You can use the following methods from JComponent: ( http://download.oracle.com/javase/6/docs/api/javax/swing/JComponent.html )
void repaint(long tm, int x, int y, int width, int height)
//**Adds the specified region to the dirty region list if the component is showing.*//
void repaint(Rectangle r)
/**Adds the specified region to the dirty region list if the component is showing.*//
You can call those before redraw()
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 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();
}
}
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);
}
}
hi everyone im using netbeans 7.2.1
and was following a tutorial for keyboard input
this code should draw a circle in JFrame, which it does
but then should take arrow key input to move it, which it does not
thank you for your help :)
package gamefirstclass;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class GameFirstClass extends JFrame {
//Variables
int y, x;
//Double Buffer
private Image dbImage;
private Graphics dbg;
//Window Basics
public GameFirstClass() {
addKeyListener(new AL());
setTitle("Add window title");
setSize(800, 700);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
// main
public static void main(String[] args) {
new GameFirstClass();
}
//Controls
public class AL extends KeyAdapter {
#Override
public void keyPressed(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == event.VK_LEFT)
{
x--;
}
if (keyCode == event.VK_RIGHT)
{
x++;
}
if (keyCode == event.VK_UP)
{
y--;
}
if (keyCode == event.VK_DOWN)
{
y++;
}
}
#Override
public void keyReleased(KeyEvent event) {
}
}
//Double Buffer
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 15, 15);
repaint();
}
}
Okay, so there is one problem: your if statements!.
Basically, in your keyListener, the if statements don't execute because of the semicolon after them.
The blocks are all that remain, and the modifications to x are the same. Just remove those semicolons and I believe it will work.
Also, don't call repaint() from paintComponent(), because you are generating a lot of repaints for every time. I don't know if this matters, but you should call setFocusable(true) on your JFrame to make sure that the KeyListener works.
Good Luck!