Peter F
Peter F

Reputation: 435

Java drawn objects not updating properly

I have been playing around with Java's 2d painting tools and have hit a snag. I am attempting to move the objects. Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test extends JPanel{

private int[] location = new int[2]; 

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.red);
g.fillArc(location[0], location[1], 100, 100, 45, 90);
g.setColor(Color.black);
g.fillArc((location[0]+50-10),(location[1]+50-10), 20, 20, 0, 360);

new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setLocation((location[0]+50),50);
repaint();
System.out.println("repainting");
        }
}).start();

}

public void setLocation(int x, int y){
this.location[0] = x;
this.location[1] = y;
}


public static void main(String[] args){
JFrame jf=new JFrame();
jf.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
jf.setPreferredSize(new Dimension(300,500));
jf.setLocation(100,100);
jf.add(new Test());

jf.pack();
jf.setVisible(true);

}
}

This only paints one of the two objects to the screen... it seems to be the second one as when I change the parameters of setLocation on [1] the one object it does paint moves. Any thoughts? Thanks

Edit: Edited above code to reflect what was said below.

Upvotes: 1

Views: 146

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You are adding two components to the JFrame in a default way. This will add the components BorderLayout.CENTER and so the second component will cover and obscure the first. You will want to read up on layout managers to fix this. Also read up on Swing Timers for simple animations, since your code, even if written correctly would do no animation.

If you want to move the drawing, then

  • Use only one Test JPanel
  • Override JPanel's paintComponent(...) method, not paint(...) method.
  • call the super.paintComponent(g) method first thing in your paintComponent method override.
  • Give the Test JPanel public methods to allow outside classes to change the location without having them directly futz with the field. Make the location field (name should begin with a lower-case letter) private just to be safe.
  • Use a Swing Timer to periodically call this method and change location, then call repaint() on the JPanel.

Upvotes: 2

Related Questions