Image is not moving in applet - java

I want to move an Image ( here is rectangle ) in applet, applet draws it, but I wonder why the image is not moving? there is no compile error!
here is my code:
package game;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Gamer extends JApplet implements KeyListener
{
private int x=50,y=50;
#Override
public void init( )
{
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch( keyCode )
{
case KeyEvent.VK_UP:
if( y>0 ) //when up key is pressed and the position of the player is not on the edge
{
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN:
if( y<171 ) //when down key is pressed and the position of the player is not on the edge
{
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT:
if( x>0 )
{
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT:
if( x<285 )
{
x=x+15;
repaint();
}
break;
}
}
#Override
public void paint( Graphics g ) //will draw the background and the character
{
g.fillRect(x, y, 200, 200);
}
#Override
public void keyReleased(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
}
When I pressed my up/down/left/write arrow , the rectangle is not moving .
Please explain why ? T.I.A.

The problem is that your applet doesn't catch the KeyEvent, so your paint method does not get called.
In fact there is an issue when you want to add KeyListener to JApplet and it's not working.
Solution is to implement KeyEventDispatcher instead of KeyListener. Also I changed the size of your rectangle from 200 to 20 in order to be able to see the movements of the rectangle better:
package game;
import java.awt.Graphics;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JApplet;
public class Gamer extends JApplet implements KeyEventDispatcher {
private int x = 50, y = 50;
#Override
public void init() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
}
#Override
public void paint(Graphics g) // will draw the background and the character
{
super.paint(g); // <- added to your code to clear the background
// before re-painting the new square
g.fillRect(x, y, 20, 20);
}
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode )
{
case KeyEvent.VK_UP:
if( y>0 ) //when up key is pressed and the position of the player is not on the edge
{
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN:
if( y<171 ) //when down key is pressed and the position of the player is not on the edge
{
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT:
if( x>0 )
{
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT:
if( x<285 )
{
x=x+15;
repaint();
}
break;
}
return false;
}
}
Hope this would be helpful.

Related

How do I properly move drawn Polygon in Swing

I am currently working on a 2D game which will be a puzzle. I got everything set up, got all my pieces added to my board (called View) and they're all aligned properly.
My next step is to select a piece by MouseEvent#mousePressed to be able to move it with the arrow keys with KeyEvent#keyPressed. The issue I'm currently running into is that my pieces will repaint themself whenever I move or resize the window. If I click on one piece and want to move it, the other pieces move too (in a way, they should not since one step equals about 100 pixel).
If anyone could tell me where my issue is and give me some advice, I would appreciate it.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Puzzle {
public static void main(String[] args) {
SwingUtilities.invokeLater(Puzzle::new);
}
public Puzzle() {
JFrame frame = new JFrame("Puzzle");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
View view = new View();
view.createPieces();
frame.setContentPane(view);
view.setFocusable(true);
MouseAdapterMod listener = new MouseAdapterMod(view);
view.addMouseListener(listener);
view.addKeyListener(listener);
frame.setVisible(true);
}
}
class View extends JPanel {
final List<Piece> pieces = new ArrayList<>();
public View() {
}
void createPieces() {
Piece topLeft = new Piece(100, 100, 0, Color.YELLOW);
pieces.add(topLeft);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gc = (Graphics2D) g;
for (Piece needle : pieces) {
needle.translate(needle.getLocation().x, needle.getLocation().y);
gc.setColor(needle.color);
gc.fill(needle);
gc.draw(needle);
}
}
}
class Piece extends Polygon {
int x;
int y;
final Color color;
Point location;
Piece(int x, int y, int type, Color color) {
this.x = x;
this.y = y;
this.color = color;
this.location = new Point(x, y);
int[] arrX = new int[] { 0, 100, 100, -100, -100, 0 };;
int[] arrY = new int[] { 0, 0, -100, -100, 100, 100 };
for (int drawIndex = 0; drawIndex < arrX.length; drawIndex++) {
addPoint(arrX[drawIndex], arrY[drawIndex]);
}
}
Point getLocation() {
return location;
}
void setLocation(Point location) {
this.location = location;
}
}
class MouseAdapterMod implements MouseListener, KeyListener {
final View view;
Polygon current;
public MouseAdapterMod(View view) {
this.view = view;
}
#Override
public void mousePressed(MouseEvent e) {
for (Piece piece : view.pieces) {
if (piece.contains(e.getX(), e.getY())) {
current = piece;
System.out.println(current);
}
}
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
current.translate(0, -100);
view.repaint();
break;
case KeyEvent.VK_DOWN:
current.translate(0, +100);
view.repaint();
break;
case KeyEvent.VK_LEFT:
current.translate(-100, 0);
view.repaint();
break;
case KeyEvent.VK_RIGHT:
current.translate(+100, 0);
view.repaint();
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
(Sorry for the indent, stackoverflow is messing it up)
EDIT: But the problem is, eventually I want to move my pieces using Piece#setLocation to always keep track of their current x/y coordinates. I figured, I need to invoke Piece#getLocation in my painting to draw them based on the location but yet I do not know how. Using Piece#setLocation literally does nothing.
If you revert back to your Piece code from this question, you can move pieces by:
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
view.translatePiece(0, -100);
break;
case KeyEvent.VK_DOWN:
view.translatePiece(0, +100);
break;
case KeyEvent.VK_LEFT:
view.translatePiece(-100, 0);
break;
case KeyEvent.VK_RIGHT:
view.translatePiece(+100, 0);
break;
}
}
And adding to your view:
void translatePiece(int dx, int dy) {
if (current != null) {
current.x += dx;
current.y += dy;
repaint();
}
}
The if (current != null) { ... } test will prevent your application from crashing if you press an arrow key before clicking on a piece, which it currently does.
You could, instead of translating the Polygon, translate the location, and use it for painting:
In keyPressed, replace current.translate to translate the location instead of the whole Polygon (you could override Piece#translate to call current.getLocation().translate for example).
In View#paintComponent, replace:
needle.translate(needle.getLocation().x, needle.getLocation().y);
with
gc.translate(needle.getLocation().x, needle.getLocation().y);
and add
gc.translate(-needle.getLocation().x, -needle.getLocation().y);
at the end of your for-loop.
This will translate the whole Graphics2D to paint a polygon, and revert it after.

Learning KeyEvents

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);

Moving the ball with Key event doesn't work

So i am trying to move the ball using arrow keys and Key event ,but the ball doesn't move.If anyone can help i would gladly appreciate it ,and keep in mind that i am a beginner in java.Here is the code:
package prozor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyEvent;
#SuppressWarnings("serial")
public class prozor extends JPanel {
public int x = 0;
public int y = 0;
public boolean up,down,left,right;
public int vx,vy;
public void update(){
vx=0;
vy=0;
if(up)vy=-5;
if(down)vy=5;
if(right)vy=-5;
if(left)vy=5;
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN: down = true; break;
case KeyEvent.VK_UP: up = true; break;
case KeyEvent.VK_LEFT: left = true; break;
case KeyEvent.VK_RIGHT: right = true; break;
}
update();
}
public void moveBall() {
x +=vx;
y +=vy;
}
public void keyReleased(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN: down = false; break;
case KeyEvent.VK_UP: up = false; break;
case KeyEvent.VK_LEFT: left = false; break;
case KeyEvent.VK_RIGHT: right = false; break;
}
update();
}
#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, 20, 20);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Sample Frame");
prozor game = new prozor();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}

Java image following my cursor

I'd like to make something similar to a cursor, ( I get no errors )
So basically I get the coordinates once I enter the applet, and based on them I have my image drawn.
Here's the code... Can you please tell me where I'm wrong ? Thanks
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
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.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Z_applets extends Applet implements
KeyListener, MouseListener, MouseMotionListener {
int z = 100;
int t = 100;
// boolean gigel = true;
//----------------- Images
Image image;
//-----------------
//----------------- Mouse Coordinates
Point p = null;
int x;
int y;
//----------------------------------
Color color = Color.GREEN;
public void init() {
addKeyListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
setBackground(Color.BLACK);
g.setColor(color);
g.drawImage(image, x, y, this);
g.fillOval(z, t, 15, 15);
}
public void update(Graphics g) {
paint(g);
}
public void loadImage() {
//URL url = getClass().getResource("borat.jpg");
//image = getToolkit().getImage(url);
try {
URL url = new URL(getCodeBase(), "trollface.png");
System.out.println(getCodeBase());
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("error" + e.getMessage());
}
}
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
char option;
option = ke.getKeyChar();
switch (option) {
case 'w': {
t--;
repaint();
break;
}
case 's': {
t++;
repaint();
break;
}
case 'a': {
z--;
repaint();
break;
}
case 'd': {
z++;
repaint();
break;
}
case '1': {
color = Color.GREEN;
break;
}
case '2': {
color = Color.RED;
break;
}
case '3': {
color = Color.YELLOW;
break;
}
// case 'r':
// {
// loadImage();
// repaint();
// break;
// }
}
}
#Override
public void keyReleased(KeyEvent ke) {
}
#Override
public void mouseClicked(MouseEvent me) {
// p = me.getPoint();
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mouseEntered(MouseEvent me) {
// p=me.getPoint();
//-------Debug--------
System.out.println(p);
System.out.println(p.x);
System.out.println(p.y);
//----------------------
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent me) {
p = me.getPoint();
x = p.x;
y = p.y;
repaint();
}
}
Without knowing what problem you have exactly, I suppose the image isn't being moved.
I looks you don't register a MouseMotionListener so do that and implement the mouseMoved method.

How to move image in Applet?

I want to move the character left, right up, and down in applet, but it is not moving at all. here is my code, help please
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class drawCenter extends Applet
{
private int x,y;// the x and y of the position of the player
private BufferedImage image, pos;
public void init( )
{
try
{
image = ImageIO.read(new File("pokemonCenter.png"));
pos = ImageIO.read(new File("player/maleInGame.png"));
}
catch (IOException ex)
{
}
x = 150; y = 171;
}
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch( keyCode )
{
case KeyEvent.VK_UP: if( y>0 )
{
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN: if( y<171 )
{
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT:if( x>0 )
{
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT:if( x<285 )
{
x=x+15;
repaint();
}
break;
}
e.consume();
}
public void keyReleased(){
}
public void paint( Graphics g )
{
g.drawImage(image, 0, 0, null);
g.drawImage(pos, x, y, null);
}
}
Your code is pretending to have a KeyListener, but there is no KeyListener anywhere to be found, much less one added to a component of the GUI. Your solution: create a class that implements KeyListener or that extends KeyAdapter, and then add it to a GUI component that has focus.
Please check out: How to Write a KeyListener.
Also, I recommend that you avoid having your GUI class, your Applet, implement KeyListener since that can give the class too much to be responsible for. Better I think to either create an anonymous inner class or even a separate stand-alone class for your KeyListener.
Make your class implement KeyListener and then call super.addKeyListener(this) in your constructor. As you have it now, you're neither specifying the class implements the interface (despite implementing the methods it would need to) nor are you ever registering a listener with the Applet.
Try this.
import javax.swing.*;
import java.awt.*;
import static java.awt.event.KeyEvent.*;
public class DrawCenter extends JApplet implements KeyListener {
Image character = null;
int x = 0;
int y = 0;
public Image loadImage(String name){
return new ImageIcon(getClass().getClassLoader().getResource(name)).getImage();
}
public void init(){
character = getImage("pokemonCenter.png");
x = getWidth()/2 - character.getWidth(null)/2;
y = getHeight()/2 - character.getHeight(null)/2;
addKeyListener(this);
}
public void keyPressed(KeyEvent e){
switch (e.getKeyCode()){
case VK_LEFT: x--; break;
case VK_RIGHT: x++; break;
case VK_UP: y--; break;
case VK_DOWN: y++; break;
}
repaint();
}
public void paint(Graphics g){
g.drawImage(character, x, y, null);
}
}
If you're making a game see the game loops or try a Game-Engine (If you'r interested, go to
http://game-engine-for-java.googlecode.com/ )
You should be something like this:
package stack;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class DrawCenter extends Applet implements KeyListener{
private int x=50,y=50;// the x and y of the position of the player
public void init( ){
addKeyListener(this);
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP: if( y>0 ){ //when up key is pressed and the position of the player is not on the edge
y=y-19;
repaint();
}
break;
case KeyEvent.VK_DOWN: if( y<171 ){//when down key is pressed and the position of the player is not on the edge
y=y+19;
repaint();
}
break;
case KeyEvent.VK_LEFT: if( x>0 ){
x=x-15;
repaint();
}
break;
case KeyEvent.VK_RIGHT: if( x<285 ){
x=x+15;
repaint();
}
break;
}
}
public void keyReleased(){
}
public void paint( Graphics g ){ //will draw the background and the character
g.fillRect(x, y, 20, 20);
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}

Categories