I am quite new to the work with JFrames and Graphics in java. My longterm goal is to create a RayCast Game-World. The following code is my first approach of a rectangle moving in a jframe at its coordinates. The coordinates change when the user presses the arrow keys. However something seems to be wrong, because when i use the program the rectangle just gets drawn and creates a path. I want the rectangle just to be drawn at the position of the coordinates.
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
public class Raycast_World_2 extends JFrame implements ActionListener, KeyListener, Runnable
{
public int px,py;
int velx = 0, vely = 0;
Graphics f;
public Raycast_World_2()
{
// Instanzvariable initialisieren
px = 100;
py = 100;
setSize(1280,960);
setVisible(true);
setDefaultCloseOperation(3);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setTitle("Raycast_World-Try4_Version 3.0");
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenuItem menuItemExit = new JMenuItem("Exit");
menuFile.add(menuItemExit);
menuBar.add(menuFile);
// adds menu bar to the frame
setJMenuBar(menuBar);
}
public void actionPerformed(ActionEvent e){
update(getGraphics());
repaint();
}
public void paint(java.awt.Graphics g) {
g.setColor(Color.red);
g.fillRect(px,py,20,20);
g.dispose();
repaint();
}
public void run(){
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT){
px = px-10;
}
if(c == KeyEvent.VK_UP){
py = py -10;
}
if(c == KeyEvent.VK_RIGHT){
px = px +10;
}
if(c == KeyEvent.VK_DOWN){
py = py +10;
}
}
public void keyTyped(KeyEvent e){
}
public void keyReleased(KeyEvent e){}
}
Please explain me what im doing wrong. Thanks in advance, for helping me!
Your problem seems to be that you are not reseting the screen every time you call the 'paint' method. So what happens is that every time you run this method it takes the previous state of the screen and draws whatever you want OVER this existing state. To be more clear, it just overloads paint on the screen. All you have to do in order to fix it is to add the following line of code at the start of your paint method:
super.paint(g);
This method, called from the superclass JFrame, will make sure that all the things that were previously painted onto the screen will be erased. So your screen after this line of code will be empty and will now be painted only with whatever you paint onto it after this line of code.