Drawing on a BufferedImage

Here is the situation:
I have a 2d array of Tiles, which make up the map for my game. When the game first starts, all of the tiles are "shrouded" because I am implementing Fog Of War as you may have seen in other games like Age of Empires and Civilization. The tiles are drawn onto a BufferedImage, (with a layer of shroud on top of each tile), and that BufferedImage is used for display in the GUI.
The problem comes in when the user moves a unit into a shrouded/foggy region. Here is a snippet:
// called when a tile has been revealed to a unit
public void unshroud(Tile t){
Graphics g = buffer.getGraphics();
g.drawImage(t.getImage(),t.getX(),t.getY(),null);
}This effectively removes the shroud from the tile, but for some reason, the game goes down from 32 to 16 frames per second when I move a unit through some shroud. The FPS goes down even when the unit is erasing about 3 tiles per second. Each tile is 32x32 pixels. Thats only 3072 pixels that are drawn onto the bufferedimage per second. It shouldnt slow it down that much.
I'm guessing that the problem is something along the lines of:
When I draw a little bit on the BufferedImage, it activates a "dirty" variable, which causes java to redraw the whole bufferedImage. This is just a guess and I don't know how to solve this problem even if that is the reason.
Thanks for reading.

Why not just make the Tiles draw the fog themselves
so that the getImage() method returns a foggy tile.
The way you're doing it right now seems like a
little bit of a hack. You could put the shroud() /
unshroud() methods in the Tile class.Yes, this sounds better for most cases, but I don't think it fits with this one. The BufferedImage does not constantly call on getImage() on all of the tiles. Because the bufferedImage does not constantly redraw the tiles, the tile has to tell the bufferedimage "hey, i'm different now. redraw me"
It is this redrawing of the 32x32 pixels onto the bufferedimage that is causing the slow framerate. There has got to be a way for me to improve this speed. Maybe I should like make my own bufferedimage class or something and deal directly with the bytes?

Similar Messages

  • Drawing colored bufferedImages on greyscale BufferedImages

    I create a BufferedImage from a base black and white image like this:
    image = new ImageIcon(image).getImage();
    BufferedImage bimage =  new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bimage.createGraphics();
    g.drawImage(image, 0, 0, null);Image renders just fine in a JFrame
    I then take a color image (a .png icon file) and run it through the same process (it retains its color when test drawn on a JFrame) and then draw the resulting BufferedImage from the icon file on the original image using the g.draw(BufferedImage) method. This resulting image has the icon on it, but the icon, which was originally in color, is now in greyscale. How do I draw color images on top of black and white images and retain the color in the overlay? I have tried using the ConvertColorOp on the overlay inside the draw call and that does not do anything. Any help is greatly appreciated

    I then take a color image (a .png icon file) and run it through the same process (it retains its color when test drawn on a JFrame) and then draw the resulting BufferedImage from the icon file on the original image using the g.draw(BufferedImage) method. This resulting image has the icon on it, but the icon, which was originally in color, is now in greyscale.This requires an SSCCE. I don't really understand it: you draw colored image #1 onto #2. Then you draw #2 back onto #1, and #1 is now gray? Under normal circumstances this is impossible. But I'm probably just misunderstanding you. Hence the need for an SSCCE.
    How do I draw color images on top of black and white images and retain the color in the overlay?This I can answer: you can't. A black and white image can only contain the colors black and white. You would need to create a new image and draw the black and white one and the colored one onto the new image.

  • How do I change the background color of a BufferedImage?

    I have a program and basically what I am doing is drawing on a BufferedImage object and then painting that BufferedImage object onto the panel. By default, the background is black and it draws in white. I am easily able to change the colour for drawing by doing g2.setColor(Color.RED) for example where g2 is the Graphics2D object created by image.createGraphics(). I tried g2.setBackground(Color.WHITE) and that did not work.
    If more information is needed, just ask.
    Any help in changing the background colour of the BufferedImage would be greatly appreciated!
    Thanks in advance!

    Here is a mini-code with comments explaining my trouble:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TestBuff extends JPanel
        Graphics2D g2;
        BufferedImage image;
        public TestBuff()
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setSize(800,800);
            frame.add(this);
            frame.setVisible(true);
            image = new BufferedImage(800,800,BufferedImage.TYPE_INT_RGB);
            g2 = image.createGraphics();
            g2.setBackground(Color.RED); // I am setting the background colour here
        protected void paintComponent(Graphics g)
            g.drawImage(image, 0, 0, g2.getBackground(), this); // Why is this black instead of red?
        public static void main(String[] args)
            new TestBuff();
    }

  • How to Pass a BufferedImage? Client - Server

    Please Help!
    I've been trying to figure out how to send a BufferedImage from my client program to the server program. I'm using a socket to create the connection. The client draws into a BufferedImage and then it is sent to the server to be saved as a JPG file. I've been able to create the image if I do it locally but since a BufferedImage is not serializable I can't do this the same way with the server. So how do I get my BufferedImage from the client to the server in a manner that I can then save it as a JPG on the server? Code examples would be very much appreciated!!!
    Thanks!
    Ryan

    I guess I'm not understanding what your saying. I just need a way to get what the user draws into a jpg on the server. I have been using sockets and streams but nothing I try really seems to work. Right now I am doing this:
    Client:
    Socket client = new Socket( InetAddress.getByName( "localhost" ), 5000 );
    ObjectOutputStream output = new ObjectOutputStream( client.getOutputStream() );
    ObjectInputStream input = new ObjectInputStream( client.getInputStream() );
    try {
    ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( imageOut );
    imageOut.flush();
    encoder.encode( sig.getImage() );
    byte[] image = imageOut.toByteArray();
    output.writeObject( image );
    Server:
    public void runServer() {
    ServerSocket server;
    Socket connection;
    try
    server = new ServerSocket( 5000, 100 );
    while ( true ) {
    connection = server.accept();
    output = new ObjectOutputStream(
    connection.getOutputStream() );
    input = new ObjectInputStream(
    connection.getInputStream() );
    ObjectOutputStream toFile = new ObjectOutputStream(
    new FileOutputStream( f ) );
    ByteArrayInputStream inStream =
    new ByteArrayInputStream( (byte[]) input.readObject() );
    JPEGImageDecoder decoder =
    JPEGCodec.createJPEGDecoder( inStream );
    BufferedImage sigImage = decoder.decodeAsBufferedImage();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder( toFile );
    encoder.encode( sigImage );
    toFile.flush();
    output.close();
    input.close();
    connection.close();
    toFile.close();
    I imagine I have very ugly looking code here but I've been trying to make something work. My code does create the file but it is not a recognizable JPG file.
    Ryan

  • Problem with BufferedImage & "getGraphics()" / "createGraphics()"

    I try to create with a servlet a Graphics2D Object with the method "createGraphics()" from a BufferedImage Object. Therefore I use the following code:
    BufferedImage bufferimage=new BufferedImage(100,100,BufferedImage. TYPE_INT_RGB);
    Graphics2D g2;
    g2=bufferimage.createGraphics();
    With the Graphics2D Object I wanna draw into the BufferedImage Object:
    g2brut.drawLine(5,5,30,30);
    The servlet runs fine on a Windows-PC with Apache and Jserv. On a Linux-PC the same code doesn't work: The method createGraphics() creates a bug and the servlet doesn't run any longer.
    Hope someone could help!

    If there are no graphical components in your Linux system, like X-Windows or something, you don't have the capabilities to use the drawing package. AWT is system-dependent and without drawing routines on your system, you can't access drawing functions in Java. Assuming this is the problem, there's a package out there that gets around that by providing system-independent access to AWT. I've only heard of the problem, never faced it myself so I don't know exactly how to implement it, but my friend ran into the same problem and solved it this way.
    Here's the link: http://www.eteks.com/pja/en/
    Michael Bishop

  • How can I make a drawing stable and not disappear?

    When I draw some shapes in a panel, if another window goes over the panel, then the drawing disappears and I have to draw it again.
    How can I make the drawing stable?

    Encephalopathic wrote:
    Of course you've read the graphics tutorials, and you are doing all of your drawing in a paintComponent(Graphics g) method override, correct?Encephalopathic is correct. If you want the stuff you draw to persist, you should override paintComponent() and redraw everything there. Just because you've drawn something on a component once (say, a line or an Image) does not mean it'll be redrawn the next time the component needs to be painted. You have to re-draw your custom stuff every time a repaint event is sent to the component, and that means overriding paintComponent().
    If your component will have lots of custom painting done to it (such as if you're making a MS Paint-style program), you might want to consider drawing to a BufferedImage, then in your component's paintComponent() override, just rendering the BufferedImage. Check the documentation for more details.

  • Help me with this drawing APPLET!

    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    <applet code ='Scribble.java' width=300 height =300>
    </applet>
    public class Scribble extends Applet
    implements MouseListener,ActionListener, MouseMotionListener,ItemListener
    Choice shape;
    String msg="";
    int last_x = 0;
    int last_y = 0;
    int clickx=0,clicky=0;
    public void init()
    shape = new Choice();
    shape.add("Line");
    shape.add("FreeHand");
    shape.select("FreeHand");
    shape.addItemListener(this);
    add(shape);
    Button clear = new Button("clear");
    add(clear);
    addMouseListener(this);
    addMouseMotionListener(this);
    clear.addActionListener(this);
    public void paint(Graphics g)
    g.drawString(msg,30,40);
        public void mousePressed(MouseEvent me)
         last_x=me.getX();
         last_y=me.getY();
         clickx=me.getX();
         clicky=me.getY();
         public void mouseEntered(MouseEvent me)
         public void mouseExited(MouseEvent me)
         public void mouseReleased(MouseEvent me)
         public void mouseClicked(MouseEvent me)
         public void mouseMoved(MouseEvent me)
         public void mouseDragged(MouseEvent me)
         //For drawing Freehand
         if(shape.getSelectedItem().equals("FreeHand"))
         Graphics g = getGraphics();
         g.drawLine(last_x,last_y,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
         //For Drawing Line
         if(shape.getSelectedItem().equals("Line"))
         Graphics g = getGraphics();
         g.setColor(Color.white);
         g.drawLine(clickx,clicky,last_x,last_y);
         g.setColor(Color.red);
            g.drawLine(clickx,clicky,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
              /*For Button*/
         public void actionPerformed(ActionEvent ae)
         String str=ae.getActionCommand();
         if(str.equals("clear"))
         repaint();
         public void itemStateChanged(ItemEvent ie)
    }Now my problem is that the thing which I've used for drawing the line...I have erased the previous position of the line by drawing it in WHITE color. But the problem is that if the line was drawn over the existing line then the line which was there before gets erased as the pixel positions are turned to WHITE color. Please help me with this as I want to give the user and idea as to where the line is being drawn like in MS paint.

    One way would be to draw to a BufferedImage and then to draw the BufferedImage onto the Component. You can get the BufferedImage's Graphics instance by invoking BufferedImage.getGraphics().

  • BufferedImage turns up black

    I'm a newbie to graphics programming, so it baffles me that the space on my applet, where a BufferedImage image would normally appear, is just a black screen. I have a red rectangle that draws shortly after that and you can move it around, so I know it's not a problem with finding the images in the directory. The red rectangle responds to key presses.
    //Fields
    private BufferedImage image;
    private boolean imagecreated = false;
    public void drawMap(Graphics g)
            if(!imagecreated)
                Graphics2D g2d = image.createGraphics();
                Image tile;
                //a is a substitute for x
                for(int a=0;a<viewportsize;a++)
                    //b is a substitute for y
                    for(int b=0;b<viewportsize;b++)
                        tile = tilebuffer.fetchImage(tiles[a]);
    g2d.drawImage(tile,a*tile.getWidth(applet), b*tile.getHeight(applet), applet);
    imagecreated = true;
    g2d.dispose();
    g.drawImage(image,0,0,applet);
    }I believe the background of my applet is black because of the doublebuffering method I picked up from another website, which leads me to believe, am I drawing on the BufferedImage incorrectly? If someone could help, it would be greatly appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hello again! Morgalr I thought it'd be implied that I instantiated. I did do that in the constructor.
    I have found the solution! Instead of using an Image I turn it into a BufferedImage, and it magically worked. Odd.
    Here is the code I used:for(int b=0;b<viewportsize;b++)
           tile = tilebuffer.fetchImage(tiles[a]);
    g2d.drawImage(ImageLoader.toBufferedImage(tile),a*tile.getWidth(applet), b*tile.getHeight(applet), applet);
    }And here is the correct code (I hope it doesn't cause problems later!):for(int b=0;b<viewportsize;b++)
    tile = tilebuffer.fetchImage(tiles[a][b]);
    ImageLoader.toBufferedImage(tile); //converts an Image to a BufferedImage
    g2d.drawImage(ImageLoader.toBufferedImage(tile),a*tile.getWidth(applet), b*tile.getHeight(applet), applet);
    }Thanks to those who helped. :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help on BufferedImage

    I'm writing code to draw something on a panel and want to save the viewport to a PNG file. It works fine if I just want to save the original view of the image. But I also need to zoom in the image and still want to save only the viewport part. Currently, I just paint everything in a BufferedImage and then get the rectangle of the viewport and get the subimage of the BufferedImage. and then save it. Now comes the heap space issue. When I zoomed in to some extend, the system will crash and the error message tells me the there are not enough heap space.
    I'm wondering if there is some other way to just capture the viewport of the whole drawing and save to a bufferedimage instead of save the whole drawing to a bufferedimage every time when I zoomed in.

    Let's see if this is any more efficient.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Hashtable;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ZoomAndSave extends JPanel {
        BufferedImage image;
        Dimension size;
        double scale = 1.0;
        public ZoomAndSave(BufferedImage image) {
            this.image = image;
            size = new Dimension(image.getWidth(), image.getHeight());
            addMouseListener(ml);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            int x = (getWidth() - size.width)/2;
            int y = (getHeight() - size.height)/2;
            g2.drawImage(image,x,y,size.width,size.height,this);
        public Dimension getPreferredSize() {
            return size;
        private void save() {
            JViewport viewport = (JViewport)getParent();
            Rectangle clip = viewport.getViewRect();
            BufferedImage toSave = new BufferedImage(clip.width, clip.height,
                                             BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = toSave.createGraphics();
            g2.translate(-clip.x, -clip.y);
            g2.setClip(clip);
            paint(g2);
            g2.dispose();
            JOptionPane.showMessageDialog(null, new ImageIcon(toSave),
                                          "the image you would save",
                                          JOptionPane.PLAIN_MESSAGE);
        private JSlider getSlider() {
            int min = 0, max = 40, inc = 5;
            final JSlider slider = new JSlider(min, max, 0);
            slider.setMajorTickSpacing(5);
            slider.setMinorTickSpacing(1);
            slider.setPaintTicks(true);
            slider.setSnapToTicks(true);
            slider.setLabelTable(getLabelTable(min, max, inc));
            slider.setPaintLabels(true);
            slider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = slider.getValue();
                    scale = 1.0 + value/20.0;
                    size.width = (int)(scale*image.getWidth());
                    size.height = (int)(scale*image.getHeight());
                    repaint();
                    revalidate();
            return slider;
        private Hashtable getLabelTable(int min, int max, int inc) {
            Hashtable<Integer,JLabel> table = new Hashtable<Integer,JLabel>();
            for(int j = min; j <= max; j += inc) {
                String s = String.format("%.2f", 1.0 + j/20.0);
                table.put(Integer.valueOf(j), new JLabel(s));
            return table;
        public static void main(String[] args) throws IOException {
            String path = "images/owls.jpg";
            BufferedImage image = ImageIO.read(new File(path));
            ZoomAndSave test = new ZoomAndSave(image);
            JFrame f = new JFrame("click to save");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test));
            f.getContentPane().add(test.getSlider(), "Last");
            f.setSize(400,400);
            f.setLocation(100,200);
            f.setVisible(true);
        private MouseListener ml = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                save();
    }

  • How do I deal with missing pixel-widths?

    I apologize if this is the wrong forum. I am currently writing a GUI in swing, and I seem to be having some sort of a pixel mismatch problem. There are two verifiable symptoms so far. I have a BufferedImage that is intended to serve as a ribbon across the bottom of a larger page. I've run createGraphics() on it, and I am using that graphics object to draw hashmarks and numbers to the buffer, and thence the screen. The larger page is arranged in SpringLayout. I'm having two problems that I'm pretty sure are connected.
    - first is that the numbers that I'm drawing to the BufferedImage keep dropping pixel columns. Zeros will be drawn with the middle column gone, for example (and thus no hole). At smaller resolutions, unbolded, they can look like Cs if the drop hits the wrong spot.
    - the bottom ribbon itself goes all the way to the left edge of the page, but the numbering isn't supposed to start until a bit further in - matching up with a spring width from further up the page. The x coord used for drawing and the width spring used for layout are both drawing from the same variable, and thus should be identical, but the number and hashmark are about 4 pixels to the right of where they should be. My guess is that a detailed search would find that there are 4 columns missing between the hashmark and the edge of the screen - which would line up with the approximate frequency seen further in.
    I have tried messing with (java-native) fonts and sizes, I have tried swapping back and forth on bold, and I'm pretty sure by now that it's an error somewhere in the pixel lineup. Does anyone have any idea what causes this, or how to fix it?
    Thank you for your time.
    Fibula

    Hi, sounds like an interesting effect, but is rather hard for me to picture from just your description. A small compiling & runnable example demonstrating your problem would really help here. By the way, with "pages", do you mean panels?

  • Need help with algorithm for my paint program

    I was making a paint program with using a BufferedImage where the user draws to the BufferedImage and then I draw the BufferedImage onto the class I am extending JPanel with. I want the user to be able to use an undo feature via ctrl+z and I also want them to be able to update what kind of paper they're writing on live: a) blank paper b) graph paper c) lined paper. I cannot see how to do this by using BufferedImages. Is there something I'm missing or must I do it another way? I am trying to avoid the other way because it seems too demanding on the computer but if this is not do-able then I guess I must but I feel I should ask you guys if what I am doing is logical or monstrous.
    What I am planning to do is make a LinkedList that has the following 4 parameters:
    1) previous Point
    2) current Point
    3) current Color
    4) boolean connectPrevious
    which means that the program would basically draw the instantaneous line using the two points and color specified in paintComponent(Graphics g). The boolean value is for ctrl+z (undo) purposes. I am also planning to use a background thread to eliminate repeated entries in the LinkedList except for the last 25 components of the LinkedList (that number might change in practice).
    What do you guys think?
    Any input would be greatly appreciated!
    Thanks in advance!

    Look at the package javax.swing.undo package - UndoableEdit interface and UndoManager class.
    Just implement the interface. Store all necessary data to perform your action (colors, pixels, shapes etc.). Add all your UndoableEdits in an UndoManager instance and call undo() redo() when you need.

  • Image Quality - how to preserve it?

    I have a web application in which I draw into a BufferedImage and Graphics2d created as follows:
    BufferedImage bi = new BufferedImage(xlen,ylen,BufferedImage.TYPE_INT_BGR);
    Graphics2d g2 = bi.createGraphics();
    At this time, I am creating plots that mainly consist of horizonal and vertical lines, filled rectangles and text.
    All the coordinate values are full integers, no roundoff.
    I then create a jpg image and send it to the output stream of my servlet using the following:
    ServletOutputStream sos = response.getOutputStream();
    BufferedImage bi = sb.getPlotImage();
    response.setContentType("Image/jpg");
    ImageIO.write(bi,"jpg",sos);
    The image gets transferred to the web component of the same dimensions as the image and the result looks really bad.
    I see horizontal and vertical lines occasionally showing up as 2 pixels rather than 1 pixel wide.
    And the text looks like hammered fecal matter.
    My guess is that the resolution got hammered in either the image compression/transmission/decompression stage.
    The question is:
    How can I retain the quality of the image?
    In the two lines where I convert the image to a jg and send it to the web page
    response.setContentType("Image/jpg");
    ImageIO.write(bi,"jpg",sos);
    I am using jpg images. I am not able to get 'gif' or 'png' image types to work for some reason.
    Can anyone suggest something that I can do to retain the original resolution of my drawn images?
    I am willing to sacrifice transfer time for image quality.
    Any suggestions?

    You probably just want to use an effect, whichever one you like best. Select the button, then go to the "Window" menu, and select "Effects" to open the Effects panel. In the bottom left you'll see an "Add Effect" button, click that and experiment with your options.

  • Am I painting to an offscreen buffer correctly?

    Hi all,
    I am creating a simulation, and I want to paint the view for the simulation smoothly. Currently I have a thread that is looping around and calling repaint() every 50 ms. However, the animation is a little jerky and occasionally some parts of the view are visibly painted before others, so it looks odd (as a note, painting usually takes 30-40 ms, but occasionally spikes as high as 100 ms).
    I am trying out painting to an offscreen buffer first, but I'm not sure if I'm doing it the right way. I am using a short tutorial I found.
    I used to have a paint() method in my JComponent-extending view which used to look like:
    paint(Graphics g){
        // do a whole bunch of painting, including cycling through hundreds of
       // images and painting them to g
    }From what I could tell, I could keep this method intact, but instead of painting to the Graphics g that is passed in when repaint() is called, I could paint it to a BufferedImage, and then just paint that BufferedImage. I've posted the code below.
    However, when I try this, the painting is much, much jerkier then before. Basically it paints one half of the screen, then the other half, alternating at about a 10 hertz rate, so it's not good at all.
    Am I implementing the offscreen buffer pattern correctly? Would it not work in my case? Any suggestions? Thanks!
    The new code I used:
         private BufferedImage offImg;
          public void paint(Graphics g){
               if (getSize().width <= 0 || getSize().height <= 0)
                    return;
                  Graphics2D g2 = createGraphics2D(g);
                  draw(g2);
                  g2.dispose();
                  if (offImg != null && isShowing()) {
                    g.drawImage(offImg, 0, 0, this);
          public Graphics2D createGraphics2D(Graphics g){
              Graphics2D g2 = null;
              if (offImg == null || offImg.getWidth() != getSize().width
                      || offImg.getHeight() != getSize().height) {
                   offImg = (BufferedImage) createImage(getSize().width,
                           getSize().height);
              if (offImg != null) {
                   g2 = offImg.createGraphics();
                   g2.setBackground(getBackground());
              // .. set attributes ..
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON);
              // .. clear canvas ..
              g2.clearRect(0, 0, getSize().width, getSize().height);
              return g2;
         public void draw(Graphics g)
               // the exact same long complex code I originally had in the paint() method
           }

    except that he is using paintComponent instead of paintThat's actually a key difference. The double buffering magic that swing does starts in the JComponent's paint() method. If you override the paint() method to do your own thing, then there's a chance that you've effectively nullified double buffering for that component. That's why custom painting code goes into the the paintComponent method.
    Now, your combination of drawing to a BufferedImage and then drawing to the graphics context within the paintComponent method will+ be slower. The graphics context passed to
    public void paintComponent(Graphics g) {
    }will be to a VolatileImage 99.9% of the time. Which means you might as well directly use "g", since it's equivalent to drawing on a back image which happens to faster than BufferedImage. Drawing on an intermediate image within the paintComponent will only slow things down.
    In the event that you're painting too much and the animation is too slow, then the suggestion is to do all your drawings in a seperate thread on a back image, and then have your paintComponent(Graphics g) method paint only that image.
    public void paintComponent(Graphics g) {
        g.drawImage(theImage,0,0,null);
    }You would also decrease the sleep time in the seperate thread to try to get all the drawing done on time. You can use a BufferedImage for the back image, or with slightly more code managing - use a VolatileImage.
    Component#createVolatileImage(int width, int height);

  • Scale in java

    I need scale in java application which will show me in meters,km,cm on X and Y axis and in the panel i will draw my figure by free hand.
    I have created panel with freehand drawing feature using Paint and drawLine() APIs.
    Can any one tell me how to add scale in X,Y direction and which api has to use.
    and how I should have to co-related with pixel and real unit(meter/km/cm).?
    Application is Like Xfig application in Linux.
    thanks in advance.

    I suggest you draw to a BufferedImage then render that onto the Graphics Context of your JPanel. What this will do for you is give you a very convenient way to save and load your image that you created.
    To scale your image you can simply use Graphics.drawImage, check the API for the specific parameters, but one of the methods will give you a width and hight option.
    If you wish to overlay a grid onto your Image to view it, then render your Image to the Graphics Context of your JPanel, then draw a grid over it using a line function from Graphics or Graphics2D.

  • Stoping flicker in my applet.

    Hi everyone. I currently am drawing a bunch of objects on an applet. I am going through an array of them, and I think the flicker is because each one is drawn separately. Is there any way to draw all of them at once to avoid this?
    Here is my draw method.
         public void paint(Graphics g) {
              Graphics2D g2 = (Graphics2D) g; //Casting
              setBackground(Color.white);
              for(int j = 0; j < chessPieces.length; j++)
                   chessPieces[j].getMeasure();
                   chessPieces[j].draw(g2);
         }     // paint

    Yes, draw them all onto a BufferedImage (in another method), and then just draw the completed BufferedImage onto the display area (from within paint). paint gets called alot ...like when the mouse passes over the display ...or when the browser gets resized/repositioned etc ...like, alot. When you set the background blank and redraw your stuff, you get the flickering that you are observing. If you draw it all onto an offscreen BufferedImage first (and only when the image NEEDS to change), then the whole previously created image gets drawn each time paint is called (repeatedly) and things look smooth. You might have to figure out BufferedImage a little, but the results are well worth it.

Maybe you are looking for

  • Compression getting disabled when performing Update on partitioned tables

    Hi All, I am on Oracle Database 11g Enterprise Edition Release 11.2.0.3.0. My question is related to Oracle Compression. I have a sub-partitioned table enabled with Basic Compression. In enabled compressed state, I am updating few columns of this tab

  • Creating cache tables in the database

    I was told there are 2 ways to create the cache tables/triggers/etc. in a database. 1. Modify the ld_cache.sql file shipped with ALDSP 2.5 to use our names for the cache objects and manually run the SQL against the database. 2. In the ALDSP console,

  • ORACLE DATAGUARD and STANDBY on two LINUX   machine (64 bits and 32 bits)

    Hi there I have two Linux machines: one with Linux RH 4 Update 2 for 64 bits and the other one with Linux RH 4 Update 2 for 32 bits. I was wondering two things: 1) Is it possible to implement ORACLE DATAGUARD between these two machines? 2) Is it poss

  • Convert jar files to sda or sca

    hi friends, is there any procedure to conver jar files to sca or sda files? One of my friend gave me some jar files and asked me to deploy it thru SDM. I know that SDM can deploy only sda,sca,ear and rar files but i donno how to depoloy jar files thr

  • About DPM 2012 R2 report settings

    Hi Expert,  I configure reporting in the status report, I click on Schedule, enter E-mail and click OK, error, How to solve? Details please refer to the picture Thanks in advance!