Search code examples
javaswingjframepaintcomponent

Ellispe won't appear on jframe


I have been working with arrow keys movement and when i finally found a easy tutorial, the graphics won't draw the circle, please any help at all would be greatly appreciated!

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;
import javax.swing.Timer;


public class Plant extends JPanel implements ActionListener, KeyListener{
double x = 0, y = 0, velx = 0, vely = 0;
Timer t = new Timer(5, this);//calls action listener every 5 seconds
public Plant(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);//sets odd keys to act normal

}
public void drawGraphics(Graphics g){

super.paintComponent(g);
Graphics2D g2= (Graphics2D) g;
g2.fill(new Ellipse2D.Double(x, y, 70, 70));

}
public void actionPerformed(ActionEvent e){
repaint();//adds to x and y coordinates, then redraws them to the new coordinates
x += velx;
y += vely;


}
public void up(){
vely = -1.5;//casll when up key is pressed
velx = 0;
}
public void down(){
vely = 1.5;
velx = 0;

}
public void left(){
velx = -1.5;
vely = 0;

}
public void right(){
velx = 1.5;
vely = 0;

}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if(code == KeyEvent.VK_UP){
    up();
}
if(code == KeyEvent.VK_DOWN){
    down();
}
if(code == KeyEvent.VK_LEFT){
    left();
}
if(code == KeyEvent.VK_RIGHT){
    right();
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}

}

and here is the code for my second class, that draws the frame.

import javax.swing.JFrame;

public class BasicCharacterMovement{
public static void main(String args[]){
    JFrame j = new JFrame();
    Plant s = new Plant();
    j.add(s);
    j.setVisible(true);
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(800, 600);

}

}

Solution

  • For custom paintings in java you need to use paintComponent(Graphics g) of JComponent. In your Plant you draw ellipse in drawGraphics that's wrong. Replace your drawGraphics with:

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.fill(new Ellipse2D.Double(x, y, 70, 70));
    }
    

    That helps you.