6 Replies - 1253 Views - Last Post: 04 January 2012 - 09:09 PM Rate Topic: -----

#1 Skywalkaz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 04-January 12

Java - Can't Move JLabel

Posted 04 January 2012 - 06:18 PM

I'm trying to move a JLabel (player) around the JFrame for a game, but it won't move. Help please?


package GDefense;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class GDefense extends JFrame
{
	int WIDTH = 1280, HEIGHT = 800;
	int genhealth = 100;
	int playerhealth = 100;
	int UP = 1, DOWN = 2, LEFT = 3, RIGHT = 4;
	int Direction = LEFT;
	Container cont;
	JLabel generator = new JLabel(new ImageIcon("generator.png"));
	JLabel ghealth = new JLabel("Generator Health: "+genhealth);
	JLabel player = new JLabel(new ImageIcon("player.png"));
	JLabel phealth = new JLabel("Health: "+playerhealth);
	
	public GDefense()
	{
		super("Generator Defense");
		setSize(WIDTH, HEIGHT);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		cont = getContentPane();
		cont.setLayout(null);
		setContentPane(cont);
		cont.setBackground(Color.BLACK);
		cont.add(generator);
		cont.add(ghealth);
		cont.add(player);
		cont.add(phealth);
		ghealth.setBounds(40,40,200,50);
		ghealth.setForeground(Color.WHITE);
		phealth.setForeground(Color.WHITE);
		generator.setBounds(WIDTH/2, 350, 50, 50);
		player.setBounds(550, 357, 35, 35);
		phealth.setBounds(1140, 40, 150, 50);
		Move move = new Move();
		move.start();
	}
	
	public class Move extends Thread implements KeyListener
	{
		public void move()
		{
			addKeyListener(this);
			while(true)
			{
				try
				{
					if(Direction==UP)
						player.setBounds(player.getX(), player.getY()-5, 35, 35);
						
					if(Direction==DOWN)
						player.setBounds(player.getX(), player.getY()+5, 35, 35);
				
					if(Direction==RIGHT)
						player.setBounds(player.getX()+5, player.getY(), 35, 35);
						
					if(Direction==LEFT)
						player.setBounds(player.getX()-5, player.getY(), 35, 35);
	
					cont.validate();
					Thread.sleep(75);
				}
				catch(Exception e){}
			}
			
		}
		public void keyPressed(KeyEvent e)
		{
			if(e.getKeyChar()=='a')
			{
				Direction = LEFT;
			}
			if(e.getKeyChar()=='s')
			{
				Direction = DOWN;
			}
			if(e.getKeyChar()=='d')
			{
				Direction = RIGHT;
			}
			if(e.getKeyChar()=='w')
			{
				Direction = UP;
			}
			repaint();
		}
		public void keyTyped(KeyEvent e){}
		public void keyReleased(KeyEvent e){}
	}
	public static void main (String[] args)
	{
		new GDefense();
	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Java - Can't Move JLabel

#2 AVReidy  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 65
  • View blog
  • Posts: 431
  • Joined: 17-February 11

Re: Java - Can't Move JLabel

Posted 04 January 2012 - 06:35 PM

I'm not sure how you could move a JLabel, but I might suggest that you try using Swing graphics with a paintComponent method. I'll show you a simple animated "game" I made with Swing that allows you to change the speed of a bouncing circle.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Game {
	
	int x = 85;
	int y = 10;
	boolean by = true;
	boolean b2 = true;
	boolean o = false;
	int siy = 1;
	
	JFrame frame;
	
	public static void main(String[] args) {
		Game gui = new Game();
		gui.start();
	}
	
	public void start() {
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		DrawPanel drawPanel = new DrawPanel();
		
		JPanel panel = new JPanel();
		panel.setBackground(Color.green);
		JButton button = new JButton("Faster");
		button.addActionListener(new ButtonListener());
		panel.add(button);
		JButton button2 = new JButton("Slower");
		button2.addActionListener(new Button2Listener());
		panel.add(button2);
		
		frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
		frame.getContentPane().add(BorderLayout.NORTH, panel);
		frame.setSize(200,200);
		frame.setVisible(true);
		
		while(true) {
			if (by == true && o == false) {
				y = y + siy;
				if (y >= 140) {
					by = false;
				}
			}

			if (by == false && o == false) {
				y = y - siy;
				if (y <= 5) {
					by = true;
				}
			}
			
			drawPanel.repaint(); //<---Repaints every iteration to create an animation
			try {
				Thread.sleep(10);
			} catch(Exception ex) {}
		}
	}
	//You might want to use this:
	class DrawPanel extends JPanel {
		public void paintComponent(Graphics graphics) {
			graphics.setColor(Color.black);
			graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
			graphics.setColor(Color.green);
			graphics.fillOval(x, y, 20, 20);
		}
	}
	
	class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			siy++;
			frame.setTitle("Speed: " + siy);
		}	
	}
	
	class Button2Listener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			siy = siy - 1;
			frame.setTitle("Speed: " + siy);
		}
	}
}


I don't have much of an explanation for this, but I think if you look at the drawPanel class and its method you will be able to figure it out. Hope this was helpful!

This post has been edited by AVReidy: 04 January 2012 - 06:39 PM

Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java - Can't Move JLabel

Posted 04 January 2012 - 08:07 PM

You have at least three major glitches in your program:
- first you cannot use Thread with Swing, use a Swing Timer instead.
- Even if using thread with Thread was safe with Swing you while(true) in the constructor of move, you will never exit out of it. The thread should execute in its run() method which is empty (any you can call it you never return from the constructor) so move.start(); will never be executed
- Third your Move class implements a KeyListener but Move is not a JComponent so cannot receive KeyEvent. To receive a KeyEvent you need a JComponent that has the focus
Was This Post Helpful? 0
  • +
  • -

#4 mastrgamr  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 18
  • Joined: 30-December 10

Re: Java - Can't Move JLabel

Posted 04 January 2012 - 08:49 PM

View Postpbl, on 04 January 2012 - 10:07 PM, said:

You have at least three major glitches in your program:
- first you cannot use Thread with Swing, use a Swing Timer instead.
- Even if using thread with Thread was safe with Swing you while(true) in the constructor of move, you will never exit out of it. The thread should execute in its run() method which is empty (any you can call it you never return from the constructor) so move.start(); will never be executed
- Third your Move class implements a KeyListener but Move is not a JComponent so cannot receive KeyEvent. To receive a KeyEvent you need a JComponent that has the focus


I'm curious, I had a similar problem. Why can't you use Threads in Swing?
It worked for me when I had a self animating BufferedImage, but when I added the use of a KeyListener the image wouldn't move to my keystroke.
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java - Can't Move JLabel

Posted 04 January 2012 - 08:56 PM

View Postmastrgamr, on 04 January 2012 - 10:49 PM, said:

but when I added the use of a KeyListener the image wouldn't move to my keystroke.

http://docs.oracle.c....html#threading
Was This Post Helpful? 0
  • +
  • -

#6 mastrgamr  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 18
  • Joined: 30-December 10

Re: Java - Can't Move JLabel

Posted 04 January 2012 - 09:04 PM

View Postpbl, on 04 January 2012 - 10:56 PM, said:

View Postmastrgamr, on 04 January 2012 - 10:49 PM, said:

but when I added the use of a KeyListener the image wouldn't move to my keystroke.

http://docs.oracle.c....html#threading


hmm... so just to make sure I understand, if i use a thread with Swing, java will get confused at what event to listen to (choosing between Thread or KeyListener)?
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java - Can't Move JLabel

Posted 04 January 2012 - 09:09 PM

More than that :)
Your KeyListener method might never be called, neither the thread that actually redraw your window, until your own Thread finishes.

javax.swing.Timer and since 1.6 SwingWorker were invented to make sure that all threads get synchronized
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1