Reputation: 1
I'm trying to get the code to move the things that are drawn on the canvas. However, I don't know how to go about by it. As of now, whenever I press the key that is supposed to make the object move to the right or left, the drawn object simply disappears. However, other objects that are not supposed to move stay on the screen.
More information: When ran, the code would simply display the circle drawn. However, I think that it is perpetually being repainted as the drawing keeps flashing and blinking. When I try to press the buttons associated with the key listener, nothing happens.
After pressing the button for a few seconds, the circle disappears completely.
Here is the code that is poorly made and disorganized:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class FaceFrame extends JFrame {
private FaceCanvas face;
public FaceFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 800);
setVisible(true);
setLayout(new BorderLayout());
face = new FaceCanvas();
add(face, BorderLayout.CENTER);
}
public static void main(String args[]) {
JFrame faceFrame = new FaceFrame();
}
}
class FaceCanvas extends Canvas
{ private int xpos, ypos;
public FaceCanvas()
{
setBackground( Color.BLUE );
setSize( 300, 300 );
xpos = ypos = 50;
}
public void paint( Graphics g )
{ // override paint method by re-defining it
g.setColor( Color.WHITE );
g.drawOval( xpos, ypos, 31, 31 );
g.drawLine( xpos + 10, ypos + 20, xpos + 20, ypos + 20 );
repaint();
}
class KeyListenerTester extends JFrame implements KeyListener {
public KeyListenerTester() {
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
addX(-10);
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
}
}
public void addX(int x)
{
xpos = xpos + 10;
repaint();
}
}
Upvotes: 0
Views: 62
Reputation: 347194
Upvotes: 1