Graphics2D?

I have created the application complied with J2SDK V.1.4.2. Although there is no error but I cannot see all images loaded in the program. When I run in the browser no images appeared. Anyone can help me?
thanks
Thada Unprasert

The main trouble was in adding managePane to both the center and south parts of container. I moved the main image loading code up to init and added the isApplet boolean to select the loading method based on how the program is run, ie, as an applet or app.
//    <applet code="Thada" width="750" height="600"></applet>
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Thada extends JApplet
  Timer timerEnemy,timerEnd;
  JButton leftButton,rightButton,startButton;
  JPanel managePane;
  PaintPane paintPane;
  boolean randomEnemyX = true;
  static boolean isApplet = true;
  public void init()
    Image image[] = new Image[3];
    if(isApplet) {
      image[0] = getImage(getCodeBase(),"sky.jpg");
      image[1] = getImage(getCodeBase(),"enemy.gif");
      image[2] = getImage(getCodeBase(),"hero.gif");
      /* image[3] = getImage(getCodeBase(),"planebomb.gif");*/
    else {
    image[0] = Toolkit.getDefaultToolkit().getImage("sky.jpg");
    image[1] = Toolkit.getDefaultToolkit().getImage("enemy.gif");
    image[2] = Toolkit.getDefaultToolkit().getImage("hero.gif");
    /*image[3] = Toolkit.getDefaultToolkit().getImage("planebomb.gif");*/
    workPlace(getContentPane(),image);
  public void workPlace(Container container,Image[] image)
    timerEnemy = new Timer(100,new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        paintPane.moveEnemyY += 10;
        if (randomEnemyX == true)
          paintPane.moveEnemyX = (int)(Math.random()*650.0);
          randomEnemyX = false;
        if (paintPane.moveEnemyX > 470)
          paintPane.moveEnemyY = 0;
          randomEnemyX = true;
        if( (paintPane.moveHeroY == paintPane.moveEnemyY)
               && (paintPane.moveHeroX <  paintPane.moveHeroX + 10 )
               && (paintPane.moveHeroX > paintPane.moveEnemyX - 90 ) )
          paintPane.moveEnemyY = 0;
          randomEnemyX = true;
          paintPane.score ++;
        paintPane.repaint();
    timerEnd = new Timer(1000, new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        paintPane.endGame++;
        if (paintPane.endGame == 60)
          timerEnd.stop();
          timerEnemy.stop();
          paintPane.over = true;
        paintPane.repaint();
    startButton = new JButton("Start Game");
    startButton.setFont(new Font("Comic Sans MS",Font.PLAIN,12));
    startButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        timerEnd.start();
        timerEnemy.start();
        paintPane.over = false;
        paintPane.score = 0;
        paintPane.endGame = 0;
    rightButton = new JButton("Right");
    rightButton.setFont(new Font("Comic Sans MS",Font.PLAIN,12));
    rightButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        paintPane.rightWalk = true;
        paintPane.leftWalk = false;
        paintPane.moveHeroX += 20;
    leftButton = new JButton("Left");
    leftButton.setFont(new Font("Comic Sans MS",Font.PLAIN,12));
    leftButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        paintPane.leftWalk = true;
        paintPane.rightWalk = false;
        paintPane.moveHeroX -= 20;
    managePane = new JPanel();
    managePane.add(startButton);
    managePane.add(leftButton);
    managePane.add(rightButton);
    paintPane = new PaintPane(image);
    container.add(managePane,BorderLayout.SOUTH);
    container.add(paintPane,BorderLayout.CENTER);
  public static void main(String[] args)
    try
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName() );
    catch(Exception e){}
    Image image[] = new Image[3];
    image[0] = Toolkit.getDefaultToolkit().getImage("sky.jpg");
    image[1] = Toolkit.getDefaultToolkit().getImage("enemy.gif");
    image[2] = Toolkit.getDefaultToolkit().getImage("hero.gif");
    image[3] = Toolkit.getDefaultToolkit().getImage("planebomb.gif");
    JFrame frame = new JFrame("Sky Battle");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e){
        System.exit(0);
//    skybattle sb = new skybattle();
//    sb.workPlace(frame.getContentPane() , image);
    JApplet applet = new Thada();
    frame.getContentPane().add(applet);
    frame.setSize(new Dimension(750,600));
    isApplet = false;
    applet.init();
    applet.start();
    frame.setVisible(true);
class PaintPane extends JPanel
  Image[] pic;
  int moveEnemyX,moveEnemyY,moveHeroX,moveHeroY;
  int score,endGame;
  boolean over,rightWalk,leftWalk;
  public PaintPane(Image[] pic)
    this.pic = pic;
    score = 0;
    over = false;
    rightWalk = true;
    leftWalk = false;
    moveEnemyX = 100;
    moveEnemyY = 10;
    moveHeroX = 300;
    moveHeroY = 20;
  public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    /* Draw the sky */
    g2.drawImage(pic[1],0,0,this);
    g2.setColor(Color.blue);
    g2.setFont(new Font("Comic Sans MS",Font.BOLD,16));
    g2.drawString("Bomb : " + score,10,420);
    g2.setColor(Color.magenta);
    g2.setFont(new Font("Comic Sans MS",Font.BOLD,16));
    g2.drawString("Time : " + (60-endGame),10,440);
    if (over == true)
      g2.setColor(Color.red);
      g2.setFont(new Font("Comic Sans MS",Font.BOLD,30));
      g2.drawString("GAME OVER",230,200);
    if (rightWalk = true)
      g2.drawImage(pic[2],moveHeroX,moveHeroY,this);
    if (leftWalk = true)
      g2.drawImage(pic[2],moveHeroX,moveHeroY,this);
    g2.drawImage(pic[1],moveEnemyX,moveEnemyY,this);
}

Similar Messages

  • Weird Graphics2D situation encountered!!! please try to see this

    hello all! i've been doing an application which will display a window and is supposedly to paint its background with the GradientPaint method. i tried putting the method in a thread because i'm planning to display a moving text using the drawString in the future.
    i've encountered this wierd problem: there are times when the frame gets painted and there are times when it's not. it's more often that the frame isn't painted. and not all of the time when it is painted that the whole frame is filled with the GradientPaint.
    whenever the frame isn't painted "&&&&&&&&&&&&" from System.out.println("&&&&&&&&&&&&"); doesn't show up.
    here's my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.border.*;
    import java.awt.geom.*;
    public class Test implements ActionListener {
    public static void main(String[] args) {
    f = new TestFrame();
    f.show();
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
         FlowLayout fl = new FlowLayout(0,30,30);
    jd.setBounds(400,250,300,200);
    jd.setResizable(false);
    jd.getContentPane().setLayout(new FlowLayout(0,30,30));
    l.setFont(new Font("Serif", Font.PLAIN, 18));
    l.setLocation(0,0);
    l.setFocusable(false);
    jd.getContentPane().add(l);
         yes.setPreferredSize(new Dimension(100,50));
    yes.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    yes.setFont(new Font("Serif", Font.PLAIN, 18));
    yes.addKeyListener(new KeyHandler());
    yes.addActionListener(mp);
    InputMap map = yes.getInputMap();
    if (map != null){
    map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
    map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
    jd.getContentPane().add(yes);
    no.setPreferredSize(new Dimension(100,50));
    no.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    no.setFont(new Font("Serif", Font.PLAIN, 18));
    no.addKeyListener(new KeyHandler());
    no.addActionListener(mp);
    InputMap map1 = no.getInputMap();
    if (map1 != null){
    map1.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
    map1.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
    jd.getContentPane().add(no);
         jd.show();
    public void actionPerformed(ActionEvent e) {
    String bname = e.getActionCommand();
    if(bname=="Yes") {
    System.exit(0);
    jd.dispose();
    static class KeyHandler extends KeyAdapter {
    public void keyReleased(KeyEvent e) {     
    int keycode = e.getKeyCode();
    if(keycode==10 && yes.hasFocus()==true) {
    System.exit(0);
    static JFrame f;
    static Test t = new Test();
    static JDialog jd = new JDialog(f,"TEST");
    static JLabel l = new JLabel("Would you like to close TEST?");
    static JButton yes = new JButton("Yes");
    static JButton no = new JButton("No");
    class TestFrame extends JFrame {
    public TestFrame() {
    setBounds(wndSize.width/4,wndSize.height/4,wndSize.width/2,wndSize.height/2);
    setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    setResizable(false);
    setTitle("test");
    canvas = new JPanel();
    getContentPane().add(canvas, "Center");
    MoveThread mt = new MoveThread(canvas);
    mt.start();
    Toolkit theKit = getToolkit();
    Dimension wndSize = theKit.getScreenSize();
    Area area = new Area(new Rectangle2D.Double(0,0,510,345));
    private JPanel canvas;
    class MoveThread extends Thread {
    public MoveThread(JPanel canvas) {
    c = canvas;
    public void paintComponent() {
    Graphics2D g2 = (Graphics2D)c.getGraphics();
    g2.setPaint(new GradientPaint(0,0,Color.green,510,345,Color.white));
    System.out.println("&&&&&&&&&&&&");
    g2.fill(area);
    g2.dispose();
    public void run() {
    try {
    paintComponent();
    sleep(5);
    } catch(Exception e) { }
    private JPanel c = new JPanel();
    Area area = new Area(new Rectangle2D.Double(0,0,510,345));
    thanks for taking some time to look at this problem!
    cheers, deo

    Hi,
    First, if you expect your paintComponent() method to get called by Swing then it should have a Graphics argument.
    Second, it is normally a bad idea to get a Graphics from a component. You should use the one provided by the paintComponent() method.
    Third, it is normally a bad idea to update anything in the GUI in a separate thread. Update your model but use the SwingUtilities.invokeLater() function to update your view of the data.
    Forth, consider double buffering - draw your graphics onto an image and then use the paintComponent(Graphics g) to paint the image to the display.
    Roger

  • Printing problem with Graphics2D

    Hi, Ive got a problem with printing.
    I have a JPanel and it has among other things a button to print the component which is an instance of the class its in. This is a drawing in Graphics2D. here is the following code that is meant to do the printing:-
         if(e.getActionCommand().equals("print")){
              System.out.println("print pressed " + title);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog()){
    try { printJob.print(); }
    catch (Exception PrinterExeption) { PrinterExeption.printStackTrace();}
    public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    System.out.println("print failed");
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(pf.getImageableX(), pf.getImageableY());
    g2.setColor(Color.black);
    this.paintAll(g2);
    System.out.println("print successful");
    return Printable.PAGE_EXISTS;
    However it doesnt print and comes up with the following long message..
    java.awt.image.ImagingOpException: Unable to transform src image
    at java.awt.image.AffineTransformOp.filter(AffineTransformOp.java:263)
    at sun.java2d.pipe.DrawImage.transformImage(DrawImage.java:304)
    at sun.java2d.pipe.DrawImage.scaleBufferedImage(DrawImage.java:453)
    at sun.java2d.pipe.DrawImage.scaleImage(DrawImage.java:531)
    at sun.java2d.pipe.DrawImage.scaleImage(DrawImage.java:801)
    at sun.java2d.pipe.ValidatePipe.scaleImage(ValidatePipe.java:171)
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2875)
    at sun.print.PSPathGraphics.drawImageToPS(PSPathGraphics.java:998)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:495)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:406)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:345)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:288)
    at sun.print.PSPathGraphics.drawImage(PSPathGraphics.java:197)
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4781)
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)
    at javax.swing.JComponent.paint(JComponent.java:798)
    at java.awt.Component.lightweightPaint(Component.java:2382)
    at java.awt.Container.lightweightPaint(Container.java:1390)
    at java.awt.GraphicsCallback$PeerPaintCallback.run(GraphicsCallback.java:67)
    at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
    at java.awt.Component.paintAll(Component.java:2367)
    at DrawingMethods.print(DrawingMethods.java:833)
    at sun.print.RasterPrinterJob.printPage(RasterPrinterJob.java:1506)
    at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1078)
    at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:979)
    at DrawingMethods.actionPerformed(DrawingMethods.java:817)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1764)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:227)
    at java.awt.Component.processMouseEvent(Component.java:5093)
    at java.awt.Component.processEvent(Component.java:4890)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3598)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3439)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1585)
    at java.awt.Component.dispatchEvent(Component.java:3439)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    I dont know how to get it to work and either does a PHD mate of mine.
    Please help
    All I need is a guarenteed way to get a Graphics2D component to print
    cheers
    pmiggy

    Um I dont know if im doing something daft but I tried this like you said
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog()){
    try {
              PageFormat pageFormat = printJob.defaultPage();
              if (pageFormat.getOrientation() == PageFormat.PORTRAIT) {
              landscape = 0;} else {
                   landscape = 1;}
              System.out.println("THE ORIENTATION IS "+ landscape);
              printJob.print(); }
    catch (Exception PrinterExeption) { PrinterExeption.printStackTrace();}
    and it doesnt seem to work as I tried it both as landscape and portrait in the print dialog but landscape is always 0.
    cheers
    pmiggy

  • How can I make ANY vector  graphics with graphics2D and save on clipboard?

    I am at my wits end here, and need some help. Simply put, I have a program that creates a basic x-y graph, drawn in a jpanel. I want to create the graph as a vector (emf, eps, svg, I don't care anymore, any of them would be good). But, all I get is a jpg or bitmap.
    I tried using the infamous FreeHEP programs, but it won't recognize the output as anything but "image" which means bitmap/jpg.
         The user enters x/y data, clicks a button, which crreates a jpanel thusly:
    public class GraphMaker extends JPanel {
    static BufferedImage image = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    GraphMaker(double[] xVals, double[] yVals, double[] sems){
    setPreferredSize(new Dimension (600,500));     
    symSize = 10;
    XminV = 0;
    XmaxV = 0;
    // code here just converts input x and y's to pixel coordinates, spacing of ticks, etc...
    for (int i =0;i < ArLn; i++){
    gX[i] = xO + (gX[i] * xRat);
    gX[i] -= xStart;
    gY[i] = gY[i] * yRat;
    gY[i] = yEnd - gY;
    semVal[i] = semVal[i]*yRat;
         Ymin = yEnd - (Ymin*yRat);
         Ymax = yEnd - (Ymax*yRat);
    BufferedImage anImage = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = anImage.createGraphics();
    g2.setBackground(white);
    g2.setColor( Color.WHITE );
    g2.fillRect(0,0,600,500);
    g2.setStroke(stroke);
    // here I use the values to draw lines and circles - nothing spectacular:
              g2.setPaint(Color.blue);
              int ii = 0;
              for ( int j = 0; j < ArLn[ii]; j++ ) {
    g2.fill(new Ellipse2D.Float(LgX[ii][j] - symOffst, gY[ii][j]-symOffst, symSize,symSize));
    g2.draw(new Line2D.Float(LgX[ii][j],(gY[ii][j]-semVal[ii][j]),LgX[ii][j],(gY[ii][j]+semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]-semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]-semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]+semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]+semVal[ii][j])));
                        g2.draw(new Line2D.Float(xLoVal[ii],yLoVal[ii],xHiVal[ii],yHiVal[ii]));
    image = anImage;
    And, when the user clicks on the "copy" button, invokes this:
    public class Freep implements Transferable, ClipboardOwner {
         public static final DataFlavor POSTSCRIPT_FLAVOR = new DataFlavor("application/postscript", "Postscript");
         private static DataFlavor[] supportedFlavors = {
              DataFlavor.imageFlavor,
              POSTSCRIPT_FLAVOR,
              DataFlavor.stringFlavor
         private static JPanel chart;
         private int width;
         private int height;
         public Freep(JPanel theGraph, int width, int height) {
              this.theGraph = Graphs;
              this.width = width;
              this.height = height;
    //******This is the key method right here: It is ALWAYS imageFlavor, never anything else. How do I make this an EPS flavor?
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (flavor.equals(DataFlavor.imageFlavor)) {
    return GraphMaker.image;
    else if (flavor.equals(POSTSCRIPT_FLAVOR)) {
                   return new ByteArrayInputStream(epsOutputStream().toByteArray());
    else if (flavor.equals(DataFlavor.stringFlavor)) {
                   return epsOutputStream().toString();
              } else{
                   throw new UnsupportedFlavorException(flavor);
         private ByteArrayOutputStream epsOutputStream() throws IOException {
    EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
         public DataFlavor[] getTransferDataFlavors() {
              return supportedFlavors;
         public boolean isDataFlavorSupported(DataFlavor flavor) {
              for(DataFlavor f : supportedFlavors) {
                   if (f.equals(flavor))
                        return true;
              return false;
         public void lostOwnership(Clipboard arg, Transferable arg1) {
    The same happens with FreeHEP - I want the flavor to be EMF, but the program sees an image so it is always imageFlavor. I know I am missing something, but what, I don't know.
    thanks for your help.

    I don't think there's a built-in solution. One workaround I've seen is to create a dummy graphics class that overrides the desired drawing functions. Instead of actually drawing pixels, the object writes postscript commands to a buffer. There also seems to be commercial code that does exactly this.

  • Graphics2D.scale() producing pixelated images from vectors

    I have a set of JPanels that I am using in my game to display the interface. Each one overrides paintComponent() and draws itself using Java2D. That all works great -- you can zoom in, move around, etc. and it all looks very nice and uses affine transformations.
    I'm trying to produce very high resolution images from this interface (for use on a poster) and using scale() is creating pixelated images rather than nice, high res images of the vector data.
    My code works as follows:
    1.) Create an instance of the interface using some saved game state data.
    2.) Create a Graphics2D object from a BufferedImage object.
    3.) Scale the Graphics2D object so that the interface will fill the entire image (in my test cases, the interface is running at 800x600 normally, and the resulting image is going to be 3200x1600, so a 4x scale).
    4.) Call the interface's paint method on the Graphics2D object. Note that all of the paint methods are using calls to fill... and draw...; nothing is getting rasterized in my code.
    5.) Write out the image object to a file (PNG).
    A sample of the output is here:
    http://i176.photobucket.com/albums/w174/toupsz/ScreenShot2007-04-24_11-45-35_-0500.png
    The white circle in the upper left hand corner is drawn in between steps 4 and 5. It actually looks correct.
    Is there something I'm doing wrong? Is it a deficiency in Java itself? Is there some way to fix it?
    Any help would be most appreciated!
    Thanks!
    -Zach
    Message was edited by:
    aaasdf

    Try setting a few hints on your Graphics2D:
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

  • Please help with my Graphics2D clipping algorithm

    I'm trying to write a redeye removal function which has the user click on an image to create a Stack of Circle(s) where the pupils are, then "clips" the circle(s) and applys a RasterOp against the pixels inside the clip. I found an example here (http://java.sun.com/mailers/techtips/corejava/2006/tt0923.html) and modified it to fit my needs. (Code below)
    My problem is that it seems like I'm applying the RasterOp filter against the entire source (BufferedImage) and then compositing the result it on top of the source using the alpha channel. This could be a 10MP photo!
    How can I make this more efficient by just applying the RasterOp against the Shape(s) which make up the clip? I tried a couple of ways, but I can't figure it out. Is there a better way to do this?
    [ filterShape is called from public void paintComponent( Graphics g )]
         public void filterShape(Graphics g, Stack<Rectangle> redeyes) {
    //          Create a translucent intermediate image in which we can perform
    //          the soft clipping
              GraphicsConfiguration gc = ((Graphics2D) g).getDeviceConfiguration();
              BufferedImage img = gc.createCompatibleImage(this.getWidth(), this.getHeight(), Transparency.TRANSLUCENT);
              Graphics2D g2 = img.createGraphics();
    //          Clear the image so all pixels have zero alpha
              g2.setComposite(AlphaComposite.Clear);
              g2.fillRect(0, 0, this.getWidth(), this.getHeight());  // sets the background to transparent
    //          Render our clip shape into the image.  Note that we enable
    //          antialiasing to achieve the soft clipping effect.  Try
    //          commenting out the line that enables antialiasing, and
    //          you will see that you end up with the usual hard clipping.
              g2.setComposite(AlphaComposite.Src);
              g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2.setColor(Color.WHITE); // sets the mask for opaque
              for(int i=0;i<redeyes.size();i++) {
                   Rectangle r = redeyes.elementAt(i);
                   Ellipse2D.Float circle = new Ellipse2D.Float(r.x, r.y, r.width, r.height);
                   g2.clip((Shape)circle);
              g2.fillRect(0, 0, this.getWidth(), this.getHeight());
    //          Here's the trick... We use SrcAtop, which effectively uses the
    //          alpha value as a coverage value for each pixel stored in the
    //          destination.  For the areas outside our clip shape, the destination
    //          alpha will be zero, so nothing is rendered in those areas.  For
    //          the areas inside our clip shape, the destination alpha will be fully
    //          opaque, so the full color is rendered.  At the edges, the original
    //          antialiasing is carried over to give us the desired soft clipping
    //          effect.
              g2.setComposite(AlphaComposite.SrcAtop);
              BufferedImage clipBI = FotoFix.applyRedeyeFix((BufferedImage)this.image);
              g2.drawImage(clipBI, 0, 0, this.getWidth(), this.getHeight(), null);
              // paint the whole g2 red to see if clip constrains the paint
    //          g2.setColor(Color.RED); // sets the mask for opaque
    //          g2.fillRect(0, 0, this.getWidth(), this.getHeight());
              g2.dispose();
              g.drawImage(img, 0, 0, null);
         }NOTE: The code works for a Stack.size()=1 right now, still debugging to add multiple redeyes to the clip.

    @posiedee 
    Thank you for using HP Support Forum. I have sent you a private message. If you’re unsure how to check your private messages please click here.
    Thank you,
    Omar
    I Work for HP

  • Graphics2D does not work in IE

    the problem i'm facing is that when i run an applet, using Graphics2D class, in the appletviewer it works fine but the same applet does'nt work in the internet explorer and gives the runtime errors
    com.ms.security.SecurityException[flag.paint]: java.IO.Exception:bad path: d:\jdk1.2.2\bin\java\awt\Graphics2D.class
    java.lang.ClassNotFoundException: java.awt.Graphics2D

    java.IO.Exception:bad path:
    d:\jdk1.2.2\bin\java\awt\Graphics2D.class
    java.lang.ClassNotFoundException: java.awt.Graphics2Dif you are using ie's internal java VM (tools/internet/advanced/java), you are limited to jre1.1 - anything added post 1.1 will not be recognised.
    Graphics2D came in in 1.2. the error messages you get confirm this.
    You could package Graphics2D in a .jar along with yr applet, if you must.
    it's a pain, but if yr writing for ie, 1.1 classlib is all you get.
    Adrian

  • Using Graphics2D from a method

    Hello everyone, I am still trying to make a method that will use Graphics2D to draw a line etc...
    Here is what I tried...
    int drawx() {
    Graphics2D g2D = (Graphics2D)g; // Get a 2D device context
    g2D.setPaint(Color.blue);
    Point2D.Float h2a = new Point2D.Float(1, 2);     
    return 1;
    This simply told me it could not find g, well earlier on in the code I obviously made a paint method..
    public void paint(Graphics g)
    So if anyone can tell me how to link them I will give dukes simple as that

    No !!! your paint code doesn't have to be 1000 line long.
    you can split the code to the paint method in to multiple method, just pass the graphics into them.
    paint(Graphics g){
       paintBackground(g);
       paintBorder(g);
       paintComponent(g);
    // implements those paintMethods();or if you want code reuse then split the paintting code into component just like implement new component
    class MyComponent {
      paint(Graphics g){
        / paint whatever
    class MyComponent2 {
      paint(Graphics g){
        / paint whatever
    class MyFrame extends JFrame{
      // now create many instance of MyComponent and MyComponent2
      paint(Graphics g){
        // for each component
       component.paint(g);

  • Unexpected clipping using draw transform in Graphics2D

    My current project needs to be able to take arbitrary sized images and size them to a fixed size on the screen. It also has to rotate them through 90 degrees.
    I have code to do this which (omitting a few details) looks like this.:
    int dynamicImageWidth = // the actual display width we are after
    int dynamicImageHeight = // the actual display height we are after
    Image img = // .. some source Image outside our control
    Graphics2D g = // .. some Graphics we are drawing to.
    if ( img.getHeight() != dynamicImageHeight || img.getWidth() != dynamicImageWidth ) {
    double sx = (double) dynamicImageWidth / img.getWidth();
    double sy = (double) dynamicImageHeight / img.getHeight();
    g.scale( sx, sy );
    g.rotate( Math.PI * 90.0 / 180.0 );
    g.drawImage( img, 0, -img.getHeight(), null );
    This works just fine when the image is the same size or larger than the display rectangle but when it is smaller I get the right scaling but the output image is is clipped to the source image's size.
    What is actually happening?

    This is much easier if you separate the scaling and rotation operations.
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.IOException;
    import javax.swing.*;
    public class ScaleAndRotate extends JPanel
        BufferedImage image;
        final int
            WIDTH  = 120,
            HEIGHT = 160;
        public ScaleAndRotate(BufferedImage image)
            this.image = getScaledImage(image);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            Rectangle2D clip = new Rectangle2D.Double(0, 0, WIDTH, HEIGHT);
            AffineTransform at = AffineTransform.getRotateInstance(Math.PI / 2);
            at.translate(0, - image.getHeight());
            //at.setToIdentity();
            g2.drawRenderedImage( image, at );
            g2.setPaint(Color.red);
            g2.draw(at.createTransformedShape(clip));
            at.setToTranslation(150,150);
            g2.drawRenderedImage( image, at );
            g2.setPaint(Color.blue);
            g2.draw(at.createTransformedShape(clip));
        private BufferedImage getScaledImage(BufferedImage in)
            int w = in.getWidth();
            int h = in.getHeight();
            double scale = getScale(w, h);
            int width  = (int)(scale * w);
            int height = (int)(scale * h);
            int dx = width  > WIDTH  ? width  - WIDTH  : 0;
            int dy = height > HEIGHT ? height - HEIGHT : 0;
            width -= dx;
            height -= dy;
            BufferedImage out = new BufferedImage(width, height, in.getType());
            Graphics2D g2 = out.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            AffineTransform at = AffineTransform.getTranslateInstance(-dx/2, -dy/2);
            at.scale(scale, scale);
            g2.drawImage(in, at, this);
            g2.dispose();
            return out;
        private double getScale(int imageWidth, int imageHeight)
            double sx = (double) WIDTH  / imageWidth;
            double sy = (double) HEIGHT / imageHeight;
            double scale = //Math.max(sx, sy);  // scale to fill
                           Math.min(sx, sy);    // scale to fit
            return scale;
        public static void main(String[] args) throws IOException
            String path = "images/cougar.jpg";       // 195, 296
                          //"images/geek-----.gif";  // 83, 67
            BufferedImage image = ImageIO.read(ScaleAndRotate.class.getResource(path));
            ScaleAndRotate sar = new ScaleAndRotate(image);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(sar);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • I want to make gImage Class extends Image and use Graphics2D

    Sorry, my english short...
    I want to make gImage Class extends Image and use Graphics2D
    I trying to do...
    make class gImage..
    extends Image class. (Inheritance)
    but Image class is abstract class..
    And I want to use gImage class same as Image class.
    I can't use constructor... because by Abstract calss...
    How do i?
    Help me.. plz...
    And I want to use Graphics2D at Applet Game, But not use Java JDK Plug-in...
    No Way?

    You need to use BufferedImage with 2D or RenderedImage with JAI.
    BufferedImage effectivley extends an Image so you can
    draw it to screen in paintCOmponent.
    I use an Extended JPanel to draw an image in a Panel with this.
    MArk

  • Negative coordinates in Graphics2d

    Hi,
    I have to apply some transformations to a BufferedImage that I draw on a JPanel; to do this, I use a matrix in which I store the scale, translation and rotation factors (similarly to the process using AffineTransformation).
    When I draw a point on that image, I would know if the point belongs to the image or it's out of the bounds and, if necessary, translate it.
    So far, I have only tested if the point's coordinates fall within the width/heigth of the image, but this has turned out unsuccessful because I've realized that there are also negative coordinates.
    Any advice is welcome! Thanks

    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class XPoints extends JPanel {
        Rectangle origRect = new Rectangle(50, 100, 200, 150);
        Shape xShape;
        AffineTransform at;
        Point[] pts;
        public XPoints() {
            int[][] coords = {
                {  75, 120, 185, 210 },
                { 190, 155, 125, 225 }
            pts = new Point[coords[0].length];
            for(int i = 0; i < coords[0].length; i++) {
                pts[i] = new Point(coords[0], coords[1][i]);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    if(at == null) initTransform();
    g2.setPaint(Color.blue);
    g2.draw(origRect);
    for(int i = 0; i < pts.length; i++) {
    g2.fill(new Ellipse2D.Double(pts[i].x-1.5, pts[i].y-1.5, 4, 4));
    // Draw transformed primitives.
    g2.setPaint(Color.red);
    g2.draw(xShape);
    Point2D.Double p = new Point2D.Double();
    for(int i = 0; i < pts.length; i++) {
    at.transform(pts[i], p);
    g2.fill(new Ellipse2D.Double(p.x-1.5, p.y-1.5, 4, 4));
    private void initTransform() {
    double x = 125;
    double y = 100;
    double theta = Math.toRadians(45);
    double cx = origRect.getCenterX();
    double cy = origRect.getCenterY();
    at = AffineTransform.getTranslateInstance(x,y);
    at.rotate(theta, cx, cy);
    xShape = at.createTransformedShape(origRect);
    public Dimension getPreferredSize() {
    return new Dimension(400,400);
    public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new XPoints());
    f.pack();
    f.setLocation(100,100);
    f.setVisible(true);

  • I think this is a bug with rendering a string to a graphics2d

    Hiya,
    The following lines of code create the rendering error I am experiencing, to which I have tested on several computers.
    BufferedImage bi=new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d=bi.createGraphics();
    g2d.setColor(new Color(1f,0f,0f,0.5f));
    g2d.fillRect(0,0,100,100);
    RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    RenderingHints rh=new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    renderingHints.add(rh);
    rh=new RenderingHints(RenderingHints.KEY_ALPHA_INTERPOLATION,RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    renderingHints.add(rh);
    g2d.setRenderingHints(renderingHints);
    g2d.setFont(new Font("Lucida",Font.BOLD,14));
    g2d.setColor(Color.BLACK);
    g2d.drawString("SQOWTGBC",10,30);
    When the destination image has an alpha of 1 the text is rendered with the correct antialiasing. However, in this example where the alpha is 0.5 the text is rendered with unwanted artifacts.
    [http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash4/269344_590137484330481_704825569_n.jpg]
    This image has JPG artifacts but the unwanted rendering artifacts are still visible (ie the brighter edges)
    I am wondering if this is not in fact an error but the intended result. If so, how to I configure the graphics object to render the antialiased text without the artifacts?
    I could not find where to submit a bug on the oracle website for the life of me so maybe if someone would like to explain how this is achieved I will be very grateful.
    Penny
    x
    I have spent several hours trying to find if this has been reported as a bug or if there is a solution posted online but to no avail.
    Edited by: 995038 on Mar 20, 2013 5:32 AM
    Edited by: 995038 on Mar 20, 2013 5:33 AM
    Edited by: 995038 on Mar 20, 2013 5:36 AM

    I have made a work around for the moment.
    This work around uses a BufferedImage to render the antialiased text first which does not create the artefacts and then draw the image of the text to where the text should appear. I dont think this is an acceptable solution because in the case where there could be 1000s of TextLayout objects the increased overhead would be unacceptable.
    private void drawTextLayout(Graphics2D g2d,float x,float _y) {
    Rectangle r=_g2d.getClipBounds();
    bufferG2D.translate(r.x,r.y);
    Composite c=bufferG2D.getComposite();
    bufferG2D.setComposite(clearComposite);
    bufferG2D.fill(r);
    bufferG2D.setComposite(c);
    textLayout.draw(bufferG2D,_x,_y);
    bufferG2D.translate(-r.x,-r.y);
    _g2d.drawImage(buffer,r.x,r.y,null);
    the BufferedImage of bufferG2D would need to be large enough to cater for any size of text to be rendered to which I believe the size should be set to the screen size. This solution requires that there always be a _g2d clip assigned.
    Regards
    Penny

  • How to render string in graphics2d by draw pixels for each string....

    How do you draw a text of graphics2d onto screen? BUT without using the drawstring method which just prints the text out.
    What i basically want is to render the text, one pixel of the text string at a time.
    for e.g. say i want to draw the word "hello", what i want is that it starts at letter "H" by drawing pixel of top to bottom at a speed which i can control (latter stuff)

    This would be a good starting point:
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class PerPixelStringRenderDemo extends JFrame {
         private PerPixelStringRenderPanel cp;
         public PerPixelStringRenderDemo() {
              Font font = new Font("Sans Serif", Font.ITALIC, 48);
              cp = new PerPixelStringRenderPanel(font, "Hello, World!", false);
              cp.setDelay(0, 100);
              setContentPane(cp);
              setTitle("Per-Pixel String Rendering");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              pack();
         public void setVisible(boolean visible) {
              super.setVisible(visible);
              if (visible) {
                   cp.start(true);
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        new PerPixelStringRenderDemo().setVisible(true);
         private class PerPixelStringRenderPanel extends JPanel implements Runnable {
              private BufferedImage bi;
              private Thread timerThread;
              private int pixelCount, maxPixelCount;
              private int delayMillis, delayNanos;
              private boolean lineOriented;
              public PerPixelStringRenderPanel(Font font, String text,
                                                      boolean lineOriented) {
                   this.lineOriented = lineOriented;
                   bi = createImage(font, text);
                   setDelay(1, 0);
              private BufferedImage createImage(Font font, String text) {
                   FontMetrics fm = getFontMetrics(font);
                   int width = fm.stringWidth(text);
                   int height = fm.getHeight();
                   maxPixelCount = width * height;
                   BufferedImage bi = new BufferedImage(width, height,
                                                      BufferedImage.TYPE_INT_ARGB);
                   setPreferredSize(new Dimension(width, height));
                   int y = fm.getAscent();
                   Graphics2D g2d = (Graphics2D)bi.createGraphics();
                   g2d.setFont(font);
                   g2d.setColor(Color.BLACK);
                   g2d.drawString(text, 0,y);
                   g2d.dispose();
                   return bi;
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   int w = bi.getWidth();
                   int drawnRowCount = pixelCount/w;
                   g.drawImage(bi, 0,0,w+1,drawnRowCount+1, 0,0,w+1,drawnRowCount+1,null);
                   int remaining = pixelCount%w;
                   g.drawImage(bi, 0,drawnRowCount+1, remaining+1,drawnRowCount+2,
                                       0,drawnRowCount+1, remaining+1,drawnRowCount+2,
                                       null);
              public void run() {
                   pixelCount = 0;
                   while (pixelCount<maxPixelCount) {
                        try {
                             Thread.sleep(delayMillis, delayNanos);
                        } catch (InterruptedException ie) {
                             break; // Thread stopped via interrupt()
                        repaint();
                        pixelCount += lineOriented ? bi.getWidth() : 1;
              public void setDelay(int millis, int nanos) {
                   delayMillis = millis;
                   delayNanos = nanos;
              public void start(boolean reset) {
                   stop();
                   if (reset) {
                        pixelCount = 0;
                   timerThread = new Thread(this);
                   timerThread.start();
              public void stop() {
                   if (timerThread!=null) {
                        timerThread.interrupt();
                        try {
                             timerThread.join();
                        } catch (InterruptedException ie) {}
                        timerThread = null;
    }It allows you to toggle between drawing one pixel at a time and one row of pixels at a time. If you do the former (what you asked for in this post), you'll have to set the delay pretty low, as it takes longer than you think to draw each pixel individually. If you do the latter, you'll want to set the delay much higher (in the milliseconds), because it's very fast to draw 1 line at a time.

  • Problem change Graphics2D into jpg

    this is part of the code i have
    private void drawPawn(Graphics2D gr, Integer pawn, Color c) {
              Coordinate coord = parent.getGameCore().currentBoard().getCoordinate(
                        pawn);
              int y = coord.getLine();
              int x = coord.getRow();
    // Image Image1; <-------------------------this is first try
    // Toolkit toolkit = Toolkit.getDefaultToolkit();
    // Image1 = toolkit.getImage("kangaroo.jpg");
    // BufferedImage Image1 = null ; <--------------------------this is second try
    // try {
    // Image1 = ImageIO.read(new File("kangaroo.jpg"));
    // } catch (IOException e) {
    ImageIcon Image1 = new ImageIcon("kangaroo.jpg"); <--------------------------and last try but it doesnt work(cant view the jpg)
              gr.setColor(borderPawnsColor);
              gr.fillOval(horizontalBorder + x * slotWidth, verticalBorder + y
                        * slotHeight, pawnDiameter + pawnBorderSize, pawnDiameter
                        + pawnBorderSize);
              gr.setColor(c);
              gr.fillOval(horizontalBorder + x * slotWidth, verticalBorder + y
                        * slotHeight, pawnDiameter, pawnDiameter);
    gr.drawImage(Image1.getImage(), horizontalBorder + x * slotWidth, verticalBorder + y
                        * slotHeight, this); <--------------------------this is where the problem place
    ive try different ways to view "kangaroo.jpg".but it doesnt work.anyone could help me?
    i get this code from googling.

    forent wrote:
    sorry..when i change the root into "E:/My Documents/NetBeansProjects/Bordeaux/src/gui/kangaroo.jpg".but why this happen?
    it solve my problem.
    yeah it called from paintcomponent().
    thanks.. :-DThat is not the root of your project, it is a direct path to your JPG. IT happened bacause your code was correct, but your JPG is in the wrong place. Your project is in "E:/MY Documents/NetBeansProjects/Bordeaux", put your JPG in there and you can access it then by just the name "kangaroo.jpg", but if you JAR your file, then you'll have to loadresource and include the JPG in your JAR to get it to work that way. In any case a direct path to your JPG will work, but you lose the ability to move your JAR freely from machine to machine as a self contained unit able to run on any appropriate JVM--you will always be requred to have that hard path "E:/My Documents/NetBeansProjects/Bordeaux/src/gui/kangaroo.jpg" to your JPG and if your friends don't have an E drive, they are just out of luck.

  • How to turn a graphics2D object into a BufferedImage

    Is there a simple way to take a Graphics 2D I have
    drawn and turn it into a BufferedImage?
    MArk

    OK, I understand now. First of all, a subimage has to be rectangular. You can't get a subimage that's an irregular shape. If you want a transparent background, we'll approach that later. First:
    // Create a BufferedImage for your original image.
    BufferedImage wholeImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = offScreen.createGraphics();
    // Set the clip region to draw in.
    g2.setClip(...);
    // Draw your entire picture to the offscreen image.
    g2.draw(...);
    // Now we want a bounding box for your clipped region.
    Rectangle clipRect = g2.getClipBounds();
    // Get a subimage from your original image that contains the clipped region.
    BufferedImage clippedImage = wholeImage.getSubimage(clipRect.getX(), clipRect.getY(), clipRect.getWidth(), clipRect.getHeight());Now you have a subimage that has the proper bounds to contain your clipped image in the smallest rectangle possible. The second image can be written to disk. The TYPE_INT_ARGB implies an alpha channel that gives you a transparent background so there's no bounding "square" wherever you decide to draw your subimage. Does this help?
    Michael Bishop

  • Saving the graphics2d to JPEG

    Hi All,
    I need a desperate solution for this problem. I am not able to save the contents of the Graphics2D content into an JPEG/GIF. could you pls tell me where I am going wrong.
    private void pathCoordinates(int iOne, int jOne, int iTwo, int jTwo,
                        double y1Diff, double x1Diff,
                      double y2Diff, double x2Diff,
                     int seriesNum, int activeTime){
       Graphics2D g2d;       
       Point2D vOne1 = at.transform(new Point2D.Double(2*jOne-1,2*iOne-1), null);
        Point2D vOne2 = at.transform(new Point2D.Double(2*jOne+1,2*iOne+1), null);
        Point2D vTwo1 = at.transform(new Point2D.Double(2*jTwo-1,2*iTwo-1), null);
        Point2D vTwo2 = at.transform(new Point2D.Double(2*jTwo+1,2*iTwo+1), null);
        double xOne = Math.floor(Math.min(vOne1.getX(),vOne2.getX()));
        double yOne = Math.floor(Math.min(vOne1.getY(),vOne2.getY()));   
        double xTwo = Math.floor(Math.min(vTwo1.getX(),vTwo2.getX()));
        double yTwo = Math.floor(Math.min(vTwo1.getY(),vTwo2.getY()));
        xOne = xOne + x1Diff + 54;
        yOne = yOne + y1Diff + 54;
        xTwo = xTwo + x2Diff + 54;
        yTwo = yTwo + y2Diff + 54;   
        Point2D.Double p1 = new Point2D.Double(xOne ,yOne );
        Point2D.Double p2 = new Point2D.Double(xTwo ,yTwo );
        debug("X1 = " + xOne + " Y1 = " + yOne  + " X2 = " + xTwo + " Y2 = " + yTwo);
        Shape line = new Line2D.Double(xOne ,yOne, xTwo ,yTwo);
             red = (int) (256 * Math.random());         
         green = (int) (256 * Math.random());          
         blue = (int) (256 * Math.random());          
        g2d = (Graphics2D)this.getGraphics();
        g2d.setPaint(new Color(red,green,blue));   
        g2d.setStroke(new BasicStroke(3));   
        g2d.draw(line);
        drawArrowHeads(yOne ,xOne, yTwo ,xTwo, g2d);
        GraphicsConfiguration gc = g2d.getDeviceConfiguration();
        // I tried this options too.. didnt work. gives me either a white or a
        // Black image.
        //  g2d.setColor(Color.white);
        //  g2d.fillRect(0, 0, width, height);
        BufferedImage image = gc.createCompatibleImage(width,height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.createGraphics();   
        g.setColor(Color.white);
        g.fillRect(0,0,width, height);
        g.dispose();
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream("screen.jpg"));
            ImageIO.write(image, "jpeg", out);
        }catch(IOException e){
             debug(e.getLocalizedMessage());
        Timer timer = new Timer();   
        timer.schedule(new TrackingTimerTask(), activeTime);
      }thanks in advance
    Domnic

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Random;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Dynamics
        public Dynamics()
            DynamicPanel dynamicPanel = new DynamicPanel();
            ImageSupport imageSupport = new ImageSupport(dynamicPanel);
            Updater updater = new Updater(dynamicPanel, imageSupport);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(updater.getUIPanel(), "North");
            f.getContentPane().add(dynamicPanel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            dynamicPanel.setImage(imageSupport.createImage());
        public static void main(String[] args)
            new Dynamics();
    class DynamicPanel extends JPanel
        BufferedImage image;
        protected void paintComponent(Graphics g)
            g.drawImage(image, 0, 0, this);
        public void setImage(BufferedImage bi)
            image = bi;
            repaint();
    class Updater
        DynamicPanel dynamicPanel;
        ImageSupport imageSupport;
        Random seed;
        int R;
        BufferedImage image;
        public Updater(DynamicPanel dp, ImageSupport is)
            dynamicPanel = dp;
            imageSupport = is;
            seed = new Random();
            R = 75;
        private void addLine()
            Point p1 = getLocation(0);
            Point p2 = getLocation(0);
            updateImage(new Line2D.Double(p1.x, p1.y, p2.x, p2.y));
        private void addCircle()
            Point p = getLocation(R);
            updateImage(new Ellipse2D.Double(p.x - R/2, p.y - R/2, R, R));
        private void addSquare()
            Point p = getLocation(R);
            updateImage(new Rectangle2D.Double(p.x - R/2, p.y - R/2, R, R));
        private Point getLocation(int pad)
            Point p = new Point();
            p.x = pad/2 + seed.nextInt(imageSupport.bi.getWidth() - pad);
            p.y = pad/2 + seed.nextInt(imageSupport.bi.getHeight() - pad);
            return p;
        private void updateImage(Shape s)
            Graphics2D g2 = imageSupport.bi.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.black);
            g2.draw(s);
            g2.dispose();
            dynamicPanel.repaint();
        public JPanel getUIPanel()
            final JButton
                line   = new JButton("line"),
                circle = new JButton("circle"),
                square = new JButton("square"),
                save   = new JButton("save");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == line)
                        addLine();
                    if(button == circle)
                        addCircle();
                    if(button == square)
                        addSquare();
                    if(button == save)
                        imageSupport.save();
                        dynamicPanel.setImage(imageSupport.createImage());
            line.addActionListener(l);
            circle.addActionListener(l);
            square.addActionListener(l);
            save.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(line);
            panel.add(circle);
            panel.add(square);
            panel.add(save);
            return panel;
    class ImageSupport
        DynamicPanel dynamicPanel;
        BufferedImage bi;
        public ImageSupport(DynamicPanel dp)
            dynamicPanel = dp;
        public BufferedImage createImage()
            int w = dynamicPanel.getWidth();
            int h = dynamicPanel.getHeight();
            bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            g2.setPaint(Color.white);
            g2.fillRect(0, 0, w, h);
            g2.dispose();
            return bi;
        public void save()
            try
                ImageIO.write(bi, "jpg", new File("dynamics.jpg"));
            catch(IOException ioe)
                System.err.println("write: " + ioe.getMessage());
    }

Maybe you are looking for