Problem in image loading on JPanel

Nikhil V G

Greenhorn

Posts: 9

posted 11 years ago

Hai all,

I have a program that to draw an image on JPanel. But in that program problem is that i cant draw image on first selecin of image. I want to select the picture twice .On second time it will draw on JPanel

void checkOSI() { // This method is responsible for creating the off-screen image. // It should be called before using the OSI. It will make a new OSI if // the size of the panel changes. if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) { // Create the OSI, or make a new one if panel size has changed. OSI = null; // (If OSI already exists, this frees up the memory.) OSI = createImage(getSize().width, getSize().height); widthOfOSI = getSize().width; heightOfOSI = getSize().height; Graphics OSG = OSI.getGraphics(); // Graphics context for drawing to OSI. OSG.setColor(getBackground()); OSG.fillRect(0, 0, widthOfOSI, heightOfOSI); OSG.dispose(); } }

public void paintComponent(Graphics g) { // Copy the off-screen image to the screen, // after checking to make sure it exists. Then, // if a shape other than CURVE is being drawn, // draw it on top of the image from the OSI. checkOSI(); g.drawImage(OSI, 0, 0, this); if (dragging && figure != CURVE) { g.setColor(dragColor); drawFigure(g,figure,startX,startY,mouseX,mouseY); } }//paintComponent

public void mouseDragged(MouseEvent evt) { // Called whenever the user moves the mouse while a mouse button // is down. If the user is drawing a curve, draw a segment of // the curve on the off-screen image, and repaint the part // of the panel that contains the new line segment. Otherwise, // just call repaint and let paintComponent() draw the shape on // top of the picture in the off-screen image. if (dragging == false) return; // Nothing to do because the user isn't drawing. mouseX = evt.getX(); // x-coordinate of mouse. mouseY = evt.getY(); // y=coordinate of mouse. if (figure == CURVE) { drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY); repaintRect(prevX,prevY,mouseX,mouseY); } else { // Repaint two rectangles: The one that contains the previous // version of the figure, and the one that will contain the // new version. The first repaint is necessary to restore // the picture from the off-screen image in that rectangle. repaintRect(startX,startY,prevX,prevY); repaintRect(startX,startY,mouseX,mouseY); }