I have the following code being called:
while(true){
view.onTick();
trySleep(55);
}
The onTick() method is described as such:
public void onTick() {
mainFrame.paintAll(mainFrame.getGraphics());
}
Here is where I set up my JFrame and JPanels etc (mainFrame is a JFrame):
private void runProgramSetup(){
JPanel canvas = new JPanel();
canvas.setLayout(new BoxLayout(canvas, BoxLayout.Y_AXIS));
mainFrame.getContentPane().add(canvas);
//create the main game panel
mapPanel = new MapPanel(model, this);
mapPanel.setPreferredSize(new Dimension(TOTAL_FRAME_WIDTH, MAP_PANEL_HEIGHT));
mapPanel.setBackground(Color.cyan);
//create the menu panel
menuPanel = new MenuPanel(model, this);
menuPanel.setLayout(new BoxLayout(menuPanel, 0));
menuPanel.setPreferredSize(new Dimension(TOTAL_FRAME_WIDTH, MENUS_PANEL_HEIGHT));
//add the panels to the window
canvas.add(mapPanel);
canvas.add(menuPanel);
//make both panels visible
mapPanel.setVisible(true);
menuPanel.setVisible(true);
}
Now here is my problem. Everything repaints when repaintAll() is called EXCEPT mapPanel's overridden paint(Graphics g) method:
#Override
public void paint(Graphics g) {
transformedImages.transformAndStoreImages(model);
paintGrid(g);
paintScenery(g);
paintElements(g);
paintDraggedElement(g);
paintUIOverlay(g);
}
It is only called once. That is it. However, every other component continues to repaint. It is only mapPanel that paints once. Here is what is even more strange. I am running on Ubuntu and get this problem. The rest of my team is running on Macs and they do not have this problem. The only way I have been able to solve this is to replace onTick() with two paint calls:
public void onTick() {
mainFrame.repaint();
mainFrame.paintAll(mainFrame.getGraphics());
}
This is all that has worked for me. I need both calls. Neither works alone. I don't like doing this though obviously because of inefficiency.. :/
Any ideas?
Thanks!
you should be overriding JPanel's
paintComponent(Graphics g)
not paint
The reason mainFrame.repaint() forces the map to refresh is because repaint() calls repaint(0, 0, 0, width, height), which marks the entire mainFrame's area to be marked as "dirty" for the RepaintManager. This is designed this way on purpose, because you usually do not want to repaint every pixel in the JFrame just to update a component. So, in onTick(), when mainFrame.paintAll() is being called, my guess is that the mapPanel's area has not been marked dirty, so the RepaintManager skips it, to save processing time. If you are very sure that you want to repaint the whole mapPanel every time onTick() is called, the simplest way would be to call mapPanel.repaint() inside of your onTick() method. This will mark the whole mapPanel as dirty so it will be redrawn asap. Also, if your menuPanel is just using regular swing JComponents, you don't need to manually cause them to repaint, they will be repainted when their values change, if you are using the API correctly.
I know this is a kind of old question, but I figured I'd answer in case anyone else runs into something similar.
Related
I am sorry about the non-descriptive title but I am not sure how to communicate the problems. For starters the JButtons every now and again are creating themselves multiple times in the same order that the loop should create them. Another issue I am having is that when I reposition them using the setLocation() method it creates new JButtons where I want them but also leaves the old ones where they are. I don't know if I just have to refresh the graphics or what is going on. Thanks for the help.
the array playerHand()is defined in the Player class and is 5 in length.
public void paintComponent(java.awt.Graphics g){
setBackground(Color.GREEN);
// create a Graphics2D object from the graphics object for drawing shape
Graphics2D gr=(Graphics2D) g;
for(int x=0;x<Player.hand.size();x++){
Card c = Player.hand.get(x); //c = current element in array
c.XCenter = 30 + 140*x;
c.XCord = c.XCenter - 30;
c.YCord = 0;
//5 pixel thick pen
gr.setStroke(new java.awt.BasicStroke(3));
gr.setColor(Color.black); //sets pen color to black
gr.drawRect(c.XCord, c.YCord, c.cardWidth-1, c.cardHeight-1); //draws card outline
gr.setFont(new Font("Serif", Font.PLAIN, 18));
gr.drawString(c.name, c.XCord+10, c.YCord+20);
gr.drawString("Atk: ", c.XCord+10, c.YCord+60);
gr.drawString(""+c.attack, c.XCord+60, c.YCord+60);
gr.drawString("Def: ", c.XCord+10, c.YCord+80);
gr.drawString(""+c.defence, c.XCord+60, c.YCord+80);
gr.drawString("HP: ", c.XCord+10, c.YCord+100);
gr.drawString(""+c.health, c.XCord+60, c.YCord+100);
JButton button = new JButton(c.name);
button.setSize(c.cardWidth, c.cardHeight);
//button.setLocation(c.XCord, c.YCord);
this.add(button);
repaint();
}
} //end of paintComponent
There are several problems (marked by "!!!!" comments) in your method below:
public void paintComponent(java.awt.Graphics g){
setBackground(Color.GREEN); // !!!!
Graphics2D gr=(Graphics2D) g;
for(int x=0;x<Player.hand.size();x++){
// .... etc ....
JButton button = new JButton(c.name); // !!!! yikes !!!!
button.setSize(c.cardWidth, c.cardHeight);
//button.setLocation(c.XCord, c.YCord);
this.add(button); // !!!! yikes !!!!
repaint(); // !!!!
}
}
Do not add components to GUI's in paintComponent(...). Never do this. Ever.
This method should be for drawing and drawing only and never for program logic or GUI building.
You do not have full control over when or if it will be called.
It needs to be as fast as possible so as not to make your program poorly responsive.
Avoid object creation within paintComponent(...) if possible.
Avoid file I/O in this method (though not a problem with your code above).
Don't call setBackground(...) in this method. Do that in the constructor or other method.
Never call repaint() from within this method.
Don't forget to call the super's paintComponent(g) method in your override.
To go over your problems:
For starters the JButtons every now and again are creating themselves multiple times in the same order that the loop should create them.
This is because you do not have control over when or how often paintComponent is called. The JVM may call it in response to information from the operating system about a dirty region, or the program may request a repaint, but for this reason, program logic and gui building should never be in this method.
Another issue I am having is that when I reposition them using the setLocation() method it creates new JButtons where I want them but also leaves the old ones where they are.
Quite likely you're seeing image remnants from your not calling the super's paintComponent method. By not doing this, you don't have the JPanel repaint itself and remove old image pixels that need to be replaced or refreshed.
I don't know if I just have to refresh the graphics or what is going on.
No, you need to change just about everything.
It looks like you have to re-think your GUI's program flow and logic and re-write a bit of code.
Here is simple example of drawing an oval.
public class SwingPainter extends JFrame{
public SwingPainter() {
super("Swing Painter");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(new MySwingComponent());
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
new SwingPainter();
}
class MySwingComponent extends JComponent {
public void paintComponent(Graphics g) {
System.out.println("paintComponent");
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(10, 10, 50, 50);
}
#Override
protected void paintBorder(Graphics g) {
System.out.println("Paint border");
super.paintBorder(g);
}
#Override
protected void paintChildren(Graphics g) {
System.out.println("Paint children");
super.paintChildren(g);
}
}
}
But in debug mode or adding some info to console before drawing (as in example), you can see that swing draws components twice.
paintComponent
Paint border
Paint children
paintComponent
Paint border
Paint children
I cannot understand why it happens, but I think it can affect performance in a difficult GUI.
The article Painting in AWT and Swing: Additional Paint Properties: Opacity suggests why: "The opaque property allows Swing's paint system to detect whether a repaint request on a particular component will require the additional repainting of underlying ancestors or not." Because you extend JComponent, the opaque property is false by default, and optimization is not possible. Set the property true to see the difference, as well as the artifact from not honoring the property. Related examples may be found here and here.
I agree with Konstantin, what you need to remember, the repaint manager is responding to any number of requests when the application starts, this typically includes the initial paint request when the window is shown and resized (there's two).
Try this. Wait till the application is running and resize the window. I'm sure you'll get more then a couple of repaint requests ;)
This works fine to me. In fact, even in debug mode the output was:
paintComponent
Paint border
Paint children
Please, bear in mind that in AWT and Swing components there are many methods (paint, paintBorder, paintChildren, paintComponent, repaint, and others) that are called via call-back, whenever the GUI engine finds suitable. That may vary from JVM to JVM or even from different execution sessions. They can also be triggered from the interaction to your program (if you minimize/maximize, for example). Or they may not, at all.
I'm currently using an animation engine I designed that takes objects of type Drawable and adds them to a List. Drawable is an interface that has one method:
public void draw(Graphics2D g2d);
The extending animation manager iterates through this list and calls the draw() method on every object, passing the Graphics2D object obtained from the Swing component.
This method seemed to work well at first, but as I feared, it seems to be unable to handle multiple objects in the long run.
With merely two Drawables registered, both drawing images on screen, I'm seeing a bit of flashing after 30-60 seconds.
Is there a way to optimize this method? It currently calls upon the AWT thread (invokeLater) to handle all of the tasks. Concurrent drawing isn't really an option as this nearly always causes issues in Swing/AWT, in large part due to the fact that Graphics isn't synchronized.
If this just simply is a bad way of animating, what is a better method when you have multiple objects that all need things rendered with their own specific variables cough game cough?
Any help would be appreciated. Thanks!
EDIT:
I can't use repaint() beacuse my engine already calls the AWT thread to paint stuff. If I call invokeLater from the AWT thread, the image never gets painted for some reason.
I should also add that I'm using a system of ticks and fps. 60 ticks # 120 fps.
Each tick updates the game logic, while each frame render calls draw on the frame manager.
Is this a bad idea? Should I just use FPS and not ticks?
I think it would be more appropriate to override paintComponent(Graphics g) and regularly call the repaint method on the JPanel or whatever you're drawing on with a Timer. Your problems may be due to to you trying to draw and then Swing doing it's own draw.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
//draw here
}
};
panel.setPreferredSize(800, 600);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true)
new Timer(16, new ActionListener() {
public void actionPerformed(ActionEvent event) {
panel.repaint();
}
}).start();
}
}
I am making a program in which there is a square that changes its x and y positions when a key is pressed. The square moves but the the old square is still there. How do I remove/clear everything from a panel before I repaint it? Calling removeAll had no effect.
Presumably your code includes custom paintComponent() logic. The key thing to observe is what does your panel look like when you do not override paintComponent()? An empty (or cleared) panel:
Thus the solution is to invoke the paintComponent() method of the parent type on the panel, before executing your custom paintComponent() logic:
public class CustomPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g); // first draw a clear/empty panel
// then draw using your custom logic.
}
}
I think this should work.
g.clearRect (0, 0, panel.getWidth(), panel.getHeight());
Also, you could keep the old location of the square and just clear that rather than clear the whole background.
I'm trying to paint a Welcome Screen for my game, but only when the game loads. I don't want it to repaint everytime during the game.
So I did this (where isStart is instantiated as true):
public myClass(String name){
setSize(800, 800);
setVisible(true);
setResizable(false);
runGame()
}
public void paint(Graphics g) {
if(nowStarting)
g.drawImage(WelcomeGameScreen, 0, 0, null);
isStart = false;
}
The problem is that the image will pop up for a second and then disappear? Oddly, it works when I leave out the if statement/isStart condition. What's wrong with this?
I am guessing that you have not copied verbatim the code, and there is an error in your code above. If your code is what I think it is...
public void paint(Graphics g) {
if(isStart)
g.drawImage(WelcomeGameScreen, 0, 0, null);
isStart = false;
}
Then at start it will draw your splash screen. But, because you are then setting isStart to false, the next time paint is called, the image will no longer be drawn. The paint method is called whenever the OS tells the screen that it needs to be refreshed (and when you force it with repaint).
The way you can get around this, is to set isStart to false in your application when the game has finished loading, and then call repaint.
I guess your newStarting boolean gets changed to false as soon as the panel is painted.
The reason it gets disappeared immediately is because of the repaints that are triggered by the Swing framework. Plus you have written the code for Welcome screen inside the overridden paint() method.
Refer this link for a detailed explanation of how to fire a splash window.
You also have a SplashScreen class in Java 1.6