Search code examples
javagraphicskeylistenergraphics2d

Java Rotate Ellipse on KeyPress


I have a basic knowledge of Java and I need to create a Sunset App. If you press right on the keyboard the sun needs to rotate at an angle. When I press the right button it will not redraw or move the ellipse, I have checked with syso if the listener works and it outputs the test so I have a problem with the rotate and the fill... can anybody help me? This is my Jpanel class...

public class OEF7 extends JPanel implements KeyListener{

private Graphics2D g2d;
private Ellipse2D sun;

public void paintComponent( Graphics g){
    super.paintComponent(g);
     g2d = (Graphics2D) g;
    g2d.setPaint(new GradientPaint(50,50,Color.RED, 100,100,Color.YELLOW,true));
    sun = new Ellipse2D.Double(0,0,50,50);
    g2d.translate(350, 200);

}

@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    if (e.getKeyCode() == 39) {
         g2d.rotate(Math.PI/10.0);
         g2d.fill(sun);
         //---- repaint() ?

        }
}

Solution

  • A Graphics object is only valid during painting. If you save it and try to use it in other methods, such as a KeyListener method, it is no longer valid. Modifying it at that point does nothing.

    Your class needs to store the rotation in a field, then make use of that field during painting:

    private double rotation;
    
    // ...
    
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            rotation = (rotation + Math.toRadians(10)) % (Math.PI * 2);
            repaint();
        }
    }