Click here to Skip to main content
15,883,894 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
The component which is motioned with KeyListener moves only to the middle of the Frame (it moves further than the middle but it visually freezes there)
I can't find my mistake.

http://www.pic-upload.de/view-27797032/java_fail.jpg.html[^]

This is my Code:

Java
package learning;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestKeyListener extends JPanel implements KeyListener {

	int x = 1, y = 1, velX = 0, velY = 1;

	public TestKeyListener() {
		addKeyListener(this);
		setFocusable(true);
		setFocusTraversalKeysEnabled(false);
	}

	public static void main(String[] args) {
		TestKeyListener board = new TestKeyListener();
		JFrame frame = new JFrame();
		frame.setTitle("Field");
		frame.setSize(500, 500);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(board);
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		g.setColor(Color.GREEN);
		g.fillOval(x, y, 50, 50);
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		System.out.println("right");
		setX(getX() + 10);
		repaint();
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

}


Best regards
Reacher7490
Posted
Comments
Richard MacCutchan 25-Jul-15 8:28am    
I have not found a solution, but I have observed that moving the rectangle in a horizontal or vertical direction, there appears to be a barrier at 250,250. I have tried setting the clip region, and the panel size, but that makes no difference. Although, I have not used Java frames for some time. I hope someone more experienced at Java GUIs will see the question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900