I'm writing a pretty simple game in Java, and I'm running into the issue of very serious flickering when I play the game as an applet in a browser. That is, all of my sprites, which are being painted on top of a background, are sometimes shown onscreen, but usually not - they repetitively flash onto the screen and then disappear. I've read that double buffering is probably the solution to this, but I'm having trouble implementing it correctly.
I'm using a JApplet as the container for a JPanel. This JPanel is the container onto which the sprites and game objects are painted - that is, in the JPanel's paintComonent method. In my JApplet, I'm using init, paint, and update override methods as follows:
Image offscreen;
Graphics bufferGraphics;
Dimension dim;
public void init(){
dim = getSize();
setBackground(Color.BLACK);
offscreen = createImage(dim.width,dim.height);
bufferGraphics = offscreen.getGraphics();
}
public void paint(Graphics g){
bufferGraphics.clearRect(0,0,dim.width,dim.height);
//here is my question - i"m not sure what I should print to bufferGraphics
g.drawImage(offscreen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
The problem I'm running into is that, at the commented line, I'm unsure of what to do to get the current applet image printed to bufferGraphics. I read an example in which the sprite was painted straight to the JApplet, without using a JPanel. In light of that, my guess is that I'd need to paint the JPanel onto bufferGraphics at the commented line. Am I on the right track here? Any help is greatly appreciated; I just would like to know any way to do this properly.
Swing is double buffered by default, there is no need to do anything special.
Your problem is probably the painting code. The code you posted is used for AWT painting, NOT Swing painting.
Custom painting is done by overriding the paintComponent() method of a JPanel or JComponent. I suggest you start by reading the Swing tutorial on Custom Painting for a working example.
Related
so when i try to create a paint method i.e.
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
}
my JFrame window will go completely black when I run my program. If I remove the paint method from the code, my normal images will appear in my JFrame window. I know FOR SURE that I am not using a .paint() method anywhere else in my code because I just added this method to my code now. Does anybody know why this is happening?
update, I am using eclipse
Start by taking a look at Performing Custom Painting and Painting in AWT and Swing to be better understand how painting works in Swing.
Basically, the paint subsystem is calling your paint method as required, when it decides that the component needs to be updated.
Because you've overridden it to basically do nothing, then nothing is painted.
As a general piece of advice, you should avoid overriding paint of top level containers like JFrame, because they are actually composite components. That is, they are actually made of a series of layers which the UI is built on
See How to use root panes for more details, but basically...
Without going into grave detail, I'm working toward creating a desktop-like program in Swing, with icons drawn on top of a background image. Usually I subclass JPanel or another JComponent and draw on that, but wanted to try something new just for kicks, and tried drawing on an instance of JFrame, without making my program a subclass of it.
I am aware that this is not the accepted way of doing this, but discovering that the image was not drawn has exposed a missing link (one of the many, I suppose) in my understanding of Swing and how it paints components.
What confuses me is that if my program subclasses JFrame and I override the paint() method (the accepted way, in other words), it will draw the image into the JFrame, but it will not do this for an instance of JFrame in my non-subclassed program.
Hopefully the code showing essentially what I want to do will help:
public class ImageLoader
{
BufferedImage img = null;
JFrame window = null;
public ImageLoader()
{
try
{
img = ImageIO.read(new File("src/strawberry.jpg"));
}catch(IOException e)
{
e.printStackTrace();
}
window = new JFrame("Strawberry Viewer");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
//Why can't I do something akin to the following to draw on an instance of JFrame?
Graphics g = window.getGraphics();
paint(g);
}
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, null);
}
public static void main(String[] args)
{
new ImageLoader();
}
}
I have read Oracle's page "Painting in AWT and Swing" but I'm still not understanding why I can't draw on an instance of JFrame. Is there any situation where I could draw on an instance of a component, or do they all have to be subclassed if I want to draw on them?
Finally, if the problem is based largely on my gross misunderstanding of how Swing works, what are some recommended books or other resources for understanding Swing?
Thanks for the help in advance. I appreciate it.
Don't use getGraphics() to do painting.
Anything you do with that Graphics object will only be temporary. Then next time Swing determines the frame needs to be repainted you will lose the painting.
In your case you use pack() so the frame is minimized. When you resize the frame, the normal frame painting will paint over your image. So try using setSize(500, 500);.
However even this won't work because your image will be painting before the normal painting has completed. Not all code is executed sequentially.
Try the following to delay the painting of the image:
try
{
Thread.sleep(1000);
Graphics g = window.getGraphics();
paint(g);
}
catch(Exception e) { e.printStackTrace(); }
When the image shows, then try resizing the frame and you will lose the image.
if my program subclasses JFrame and I override the paint() method
Don't override paint() of a JFrame (yes, it will work, but it is NOT the way painting was designed to be done in Swing). Custom painting is done by overriding paintComponent() of a JPanel and then you add the panel to the frame.
if the problem is based largely on my gross misunderstanding of how Swing works
The Swing tutorial is the best place to start for Swing basics. See the section on Custom Painting to get your started.
For a more technical article see Painting in AWT and Swing.
I am doing a project with double buffering. When I paint, it simply paints on top of the old layers, but I need to erase them. Repaint() didn't work, but I'm guessing something equally as simple is the answer.
Any ideas?
Added code, and now it disappears, but it erases the background color.
public void paint(Graphics g)
{
super.paint(buffer);
for(Projectile p: projectiles)
drawRectImage(buffer, p.image, p.getRectangle());
}
Suggestions:
If this is a Swing GUI, then don't override the paint method, but instead override the paintComponent method. This won't help your current problem, but will help prevent future problems including problems with painting of borders and child components.
If Swing (again you don't say), then make sure that your painting component extends JPanel, not JComponent, since JPanel is opaque and fills its background rectangle in its super method.
If it's not Swing, then you should strongly consider changing from AWT to Swing.
If you're still stuck, then yep, you'll want to create and post a minimal example program. Please check out the link.
A mouse listener calls repaint() and I can see that it does actually go past the drawing part because I see globalcounter incremented in the output of System.out.println(). On the screen, however, I don't see any change until I minimize the window and maximize again, resize it, or move it out of the visible screen area and back in. Obviously I'd like it to update without my intervention.
class GUI extends javax.swing.JFrame {
int globalcounter=0;
class MyCanvas extends Canvas {
#Override
public void paint(Graphics g) {
globalcounter++;
g.drawString(globalcounter,100,100);
System.out.println(globalcounter);
}
}
}
(Originally I was loading an image from a file that got constantly updated (webcam) and painting it on the canvas. When I dragged it partly out of the visible screen area and back in, the part that has been 'outside' was refreshed, the rest not.)
revalidate() instead of repaint() didn't change anything.
I know this post is a duplicate to Java repaint not working correctly but when I posted it there it was deleted.
Why are you adding an AWT component, Canvas, to a Swing component, JFrame? You should stick with Swing components only. And also do you know the size of your MyCanvas, and how have you added it to the JFrame as you don't show this code.
Consider
using a JPanel instead of a Canvas object,
drawing in its paintComponent method,
showing us an sscce if you're still stuck.
And also, if all you're doing is drawing text, use a JLabel rather than drawing in paint/paintComponent, and change its text with its setText(...) method.
I'm trying to make a paint editor with Java in which I have a toolbar with the objects that I would like to paste in the canvas. I'm using Swing components to make the GUI, but when I looked for the way of making the canvas, I only found the class canvas from AWT.
Is there any way to make something similar to canvas with Swing? (for example, JPanel?) I have read that using the class canvas from AWT with a GUI made with swing won't work correctly, is that true?
In order to make a custom 'Canvas' in swing you usually write a subclass of a JPanel. Then, you must overwrite the protected paintComponent(Graphics g) method of JPanel.
In the paint method, you can call methods on the Graphics object to actually draw on the JPanel.
As always, the Java Tutorials have a great reference on this to get you started.
You'll probably want to make a subclass of JPanel and implement your own way of painting components you want to draw onto the panel.
The basic approach will probably be along the line of assigning a MouseListener to the subclass of JPanel, then implement painting functionality.
The basic idea may be something along the line of:
class MyCanvas extends JPanel implements MouseListener
{
Image img; // Contains the image to draw on MyCanvas
public MyCanvas()
{
// Initialize img here.
this.addMouseListener(this);
}
public void paintComponent(Graphics g)
{
// Draws the image to the canvas
g.drawImage(img, 0, 0, null);
}
public void mouseClicked(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
Graphics g = img.getGraphics();
g.fillOval(x, y, 3, 3);
g.dispose();
}
// ... other MouseListener methods ... //
}
The above example is incomplete (and not tested -- it definitely won't compile), but it gives an idea about how to implement a MyCanvas class in which a user can click on and draw circles.
The img object is used to hold the image of the canvas. The paintComponent method is used to paint the img object to the canvas. In the mouseClicked method, the Graphics object associated with img is retrieved in order to fillOval onto the image.
Since one the requirements is to paste images onto the canvas, it may be a good idea to hold some Images that you want to paste into the canvas. Perhaps something along the line of:
Image[] myImages; // Used to store images to paint to screen.
Then, in the routine to paint the image onto img stored in MyCanvas:
g.drawImage(myImage[INDEX_OF_DESIRED_IMAGE], 0, 0, null);
By using the drawImage method of the Graphics object, other Images can be drawn onto Images.
As for the question on AWT and Swing, yes, it is true that you do not want to mix components from the AWT and Swing, as they differ in the way they render GUI components. AWT is based on heavyweight components, meaning they native windowing for painting the GUI, while Swing is based on lightweight components, meaning the GUI is drawn by Java itself without using native components.
A good guide on the difference of AWT and Swing is provided in Painting in AWT and Swing article from Sun.
Simply subclass JComponent.
JPanel is an inappropriate class. It is often suggested as it appears to have setOpaque(true) invoked on it automatically. It's actually the PL&F which does that, and whether or not it actually happens is implementation and vendor dependent.
Canvas is a heavyweight component. That is to say that it is controlled by the underlying windowing system. The result is that it will typically be drawn over the top of Swing components, without respect to z-order or clipping (putting it in a scroll pane will give odd behaviour).
You might want to look at the Minueto API. It is a very simple to use graphics api, and you can combine the Java event listening with it to provide your drawing capability.
http://minueto.cs.mcgill.ca/