Reputation: 515
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.
public void paint(Graphics g)
{
repaint();
mapLimits();
moveEnemy();
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();
Upvotes: 0
Views: 640
Reputation: 168825
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:
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.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)
.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.repaint()
from within either paint(Graphics)
or paintComponent(Graphics)
.Upvotes: 2