开发者

java multi class paint

I am working in a project with graphics where so far I have 2 different classes with graphics in each one. In both classes the paint(Graphics g) method is called but when I execute it, both JFrames are flickering.

My question: is that the correct way is to call all the graphics of the project in one class or new threads for each class are required?

Thank you in advance.


Code snippets

public void paint(Graphics g) 
{ 
    repaint(); 
    mapLimits();
    m开发者_JAVA百科oveEnemy();
    g.drawImage(background, 0,0, null); // draw background 
    drawImage(g, myHero, heroXposition, heroYposition, "name"); // draw hero 
    repaint(); 
}

and for the inventory class the paint method goes like this

public void paint(Graphics g) 
{ 
    g.drawImage(background, 0,0,null); //background 
    repaint(); 
} 

and both of them are called in the main class

Hero hero = new Hero(); 
hero.setVisible(true); 
Inventory inv = new Inventory(); 
inv.setVisible();


The answer has nothing to do with Thread (or rather, throwing threads at this will not solve the problems the code already has). It all comes down to custom painting, and doing it correctly.

See the Performing Custom Painting lesson of the Java Tutorial for details.

Some general tips are:

  • Never override paint(Graphics) in a top level container. The minute you do, you discover that the custom rendering might be better shown in a JDialog, JInternalFrame (etc.) rather than whatever you coded it in.
  • Instead extend one of JComponent or JPanel. The first for entirely custom painting, the second if combining custom painting with other components. In either of those classes, override paintComponent(Graphics) rather than paint(Graphics).
  • Use the common nomenclature for class & method names. Classes EachWordUpperCase, methods & attributes firstWordLowerCase, constants ALL_UPPER_CASE. This is especially important if anyone besides you will ever read the code. Other programmers use the case of names to provide hints as to their nature/source.
  • Don't call repaint() from within either paint(Graphics) or paintComponent(Graphics).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜