I'm creating a game where you use arrow keys to move your character(it's a square right now) across the screen to doge incoming objects, and I am using a timer to update the object coming across the screen, but when I click my start button to make the object move across the screen, it just freezes everything and doesn't reupdate and redraw it like I want to, any idea how to fix it?
This is my code, sorry, it may be slightly to neat and kind of spacy so hope you don't mind scrolling a bit. I hope you guys can help, i'm in highschool in my programming 2 class and my teacher doesn't work much with timers, thanks for the help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
public class Game2v4 extends Frame implements ActionListener, KeyListener
{
int x = 100;
int y = 100;
Timer myTimer = new Timer(10,this);
Panel southPanel = new Panel();
Button startButton = new Button("Start");
Button clearButton = new Button("Clear");
public Game2v4()
{
addKeyListener(this);
setFocusable(true);
this.setLayout(new BorderLayout());
southPanel.setLayout(new GridLayout(1,2));
add(southPanel, BorderLayout.SOUTH);
southPanel.add(startButton);
startButton.addActionListener(this);
southPanel.add(clearButton);
clearButton.addActionListener(this);
addWindowListener
(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_UP)
{
y = y - 5;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
y = y + 5;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
x = x + 5;
repaint();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
x = x - 5;
repaint();
}
while(x >= 400)
{
x = 1;
repaint();
}
while(x <= -10)
{
x = 400;
repaint();
}
while(y >= 400)
{
y = 1;
repaint();
}
while(y <= 0)
{
y = 400;
repaint();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void actionPerformed(ActionEvent e)
{
Graphics g = getGraphics();
if(e.getSource() == startButton)
{
for(int i=250; i>0; i-=5)
{
g.drawRect(i,300,25,25);
}
}
this.requestFocus();
}
public void paint(Graphics g)
{
g.drawRect(x,y,25,25);
}
public static void main(String[] args)
{
Game2v4 f = new Game2v4();
f.setBounds(50,100,400,400);
f.setTitle("Gamev4");
f.setVisible(true);
}
}