Basically i want to make a platform game in java purely from the java 2d graphics. I have managed to link the keyListener to update variables which my graphics pane can then use to draw my images. But i cant do is get my image to refresh after the variables are updated.
I have to classes, my keyListener and my main program (ignore class names took them off a tutorial i used for the keylistener).
Anyway here is my code for the main program
package code;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyListenerDemo extends Frame
{
public static int x = 0;
public static int y = 0;
public static void main(String[] a)
{
JFrame frame = new JFrame("Key input Console");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KeyListenerDemo test = new KeyListenerDemo();
JTextField textField = new JTextField();
frame.addKeyListener(new MyKeyListener());
// frame.add(textField);
frame.setSize(200,50);
frame.setVisible(true);
}
@SuppressWarnings("deprecation")
KeyListenerDemo()
{
super("Paint Tester");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(1024,768);
repaint();
show();
//add("Center", new CvHelloApp());
}
public void paint(Graphics g)
{
g.setColor(Color.BLUE);
g.fillOval(50+x,50+y,10,10);
}
}
and here is the code from my key listener
package code;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
class MyKeyListener implements KeyListener
{
public void keyTyped(KeyEvent e)
{
char c = e.getKeyChar();
//System.out.println("Key Typed: " + c);
}
public void keyPressed(KeyEvent e)
{
char c = e.getKeyChar();
//System.out.println("Key Pressed: " + c);
if (c == 'w')
{
KeyListenerDemo.y = KeyListenerDemo.y -5;
System.out.println("y:"+KeyListenerDemo.y);
}
if (c == 's')
{
KeyListenerDemo.y = KeyListenerDemo.y +5;
System.out.println("y:"+KeyListenerDemo.y);
}
if (c == 'a')
{
KeyListenerDemo.x = KeyListenerDemo.x -5;
System.out.println("x:"+KeyListenerDemo.x);
}
if (c == 'd')
{
KeyListenerDemo.x = KeyListenerDemo.x +5;
System.out.println("x:"+KeyListenerDemo.x);
}
}
public void keyReleased(KeyEvent e)
{
char c = e.getKeyChar();
//System.out.println("Key Released: " + c);
}
}
So basically if you run my program you can see my variables change as the w s a d keys are pressed, but what i need help with is making it so my graphics will redraw.
I know that i am using alot of bad practice in this code, right now im just focusing on getting things working then ill clean it up.
Thanks for any help,
-William