/    Sign up×
Community /Pin to ProfileBookmark

repaint(); – only one image (JPanel / Graphics)

Hi,

I am using repaint(); to show animation on a JPanel. The problem is, when I add a background to my JPanel, and then initiate the repaint(); method, it repaints my entire JPanel which is really bad for performance. My question to you is: Is there any way to specify which object I would like to repaint? Heres my example code:

[CODE]public class DrawFrame{
public int speed = 10;
public int x = 480;
public int y = 640;
public int sx = 0;
public int sy = 0;
public int ex = 480;
public int ey = 60;
public String background = “background.jpg”;
public File background2 = new File(background);
public BufferedImage image2;
public String path = “plane.gif”;
public File file = new File(path);
public BufferedImage image;
public DrawFrame() {
Container cp = this.getContentPane();
DrawingPanel dp = new DrawingPanel();
cp.add(dp);
dp.addKeyListener(this);
dp.setFocusable(true);
}
public static void main(String[] args) {
DrawFrame f = new DrawFrame();
f.setExtendedState(f.getExtendedState()|JFrame.MAXIMIZED_BOTH);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void refresh(){
repaint();
}
class DrawingPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
try {
image = ImageIO.read(file);
g.drawImage(image,x,y, this);
g.setColor(Color.red);
g.fillRect(sx, sy, 5, 15);
g.setColor(Color.green);
g.fillRect(ex, ey, 50, 50);
}
catch (IOException e) {
e.printStackTrace();
}
}

}[/CODE]

this is just a snipit of code in which i removed the part you dont need to see in order to make it easier to read.

So I’m hoping theres some way to say something like: “fillRect.repaint();” or something along those lines.

Thanks for reading,
Nate

to post a comment
Java

1 Comments(s)

Copy linkTweet thisAlerts:
@chazzyJan 18.2009 — just keepa reference as a member of the DrawFrame, and in refresh call that object's repaint method...
×

Success!

Help @Natdizzle spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...