Draw to an image using graphics object

ive been trying to this. create a starfield 800px wide and twice the height of the screen 2x600. this image would be scrolling down the screen giving the appearance of moving through space. what i did was create an image the called "starField", and created a graphics object "starFieldObj" to draw dots (stars) to this image.
is this the correct way to do this? my program seems to work differently depending on where i call "generateStarField()" which draws to "starFieldObj"
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Alpha1 extends Canvas implements Runnable, MouseMotionListener, MouseListener, KeyListener {
     private Image buffer; //bufer image
     private Graphics gfx;
     private Graphics starFieldObj;
     private Image playerShip;
     private int frames = 60; //frames per second
     private MediaTracker mediaTracker; //tracks loaded images
     private boolean ready; //ready to  start animation
     private int [] keys = new int[256];
     private int playerShipX = 100;
     private int playerShipY = 100;
     private static Random random = new Random();
     private Image starField;
     private int starFieldSpeed = 5;
     private int starFieldX = 0;
     private int starFieldY = -600;
     public static void main(String[] args)
          Alpha1 t = new Alpha1();
          Frame f = new Frame("blah");
          f.setSize(800, 600);
          f.add(t, BorderLayout.CENTER);
          f.show();
          t.start();
          t.requestFocus();
          f.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent e){
                    System.exit(0);}});
     public Alpha1()
          addKeyListener(this);
          addMouseListener(this);
          ready = false;
          mediaTracker = new MediaTracker(this);
          playerShip = getToolkit().getImage("testship1.png");
          //starField = getToolkit().getImage("testbg.png");
          //mediaTracker.addImage(playerShip, 0);
          mediaTracker.addImage(starField, 0);
          try {
               mediaTracker.waitForID(0);
          catch (InterruptedException e) {
               e.printStackTrace();
     public void start()
          buffer = createImage(getSize().width,getSize().height);
          //starField = createImage(getSize().width,getSize().height * 2);
          gfx = buffer.getGraphics();
          //starFieldObj = starField.getGraphics();
          generateStarfield();
          ready = true;
          new Thread(this).start();
     public void mouseDragged(MouseEvent e)     {}
     public void mouseMoved(MouseEvent e)     
          playerShipX = e.getX();
          playerShipY = e.getY();
     public void mouseReleased(MouseEvent e)     {}
     public void mousePressed(MouseEvent e)     {}
     public void mouseExited(MouseEvent e)     {}
     public void mouseEntered(MouseEvent e)  {}
     public void mouseClicked(MouseEvent e)     {}
     public void keyTyped(KeyEvent keyevent)     {}
     public void keyPressed(KeyEvent keyevent)
          keys[keyevent.getKeyCode()] = 1;
          System.out.println(keyevent.getKeyCode());
     public void keyReleased(KeyEvent keyevent)     
          keys[keyevent.getKeyCode()] = 0;
     public void run()
          while (true)
               if (isVisible())
                    repaint();
                    updatePositions();
               }//end if
               try 
               { Thread.sleep(1000/frames); }
               catch (InterruptedException e)
               { e.printStackTrace(); }
          }//end while
     public void paint(Graphics g) {     /*empty etc*/ }
     public void updatePositions()
          if (keys[38] == 1 & keys[40] == 0) //IF UP IS PRESSED
          { playerShipY -= 3; }
          if (keys[40] == 1 & keys[38] == 0) //IF DOWN IS PRESSED
          { playerShipY += 6; }
          if (keys[37] == 1 & keys[39] == 0) //IF LEFT IS PRESSED
          { playerShipX -= 5; }
          if (keys[39] == 1 & keys[37] == 0) //IF RIGHT IS PRESSED
          { playerShipX += 5; }
          //starFieldY = starFieldY + starFieldSpeed;
          //if (starFieldY == 0)
          //     starFieldY = -600;
          //     System.out.println("dadssa");
     public int getRandom(int from, int to)
          if (from > to)
               int randTemp;
               randTemp = from;
               from = to;
               to = randTemp;
          return random.nextInt(to-from+1)+from;
     public void generateStarfield()
          starFieldObj.setColor(Color.black);
          starFieldObj.fillRect (0, 0, 800, 600 * 2);
          for (int td=0; td < 900 ; td++) //draw 900x2 dots on 800x1200 image
                    starFieldObj.fillRect (getRandom(1,800), getRandom(1,600), 1, 1);
                    starFieldObj.fillRect (getRandom(1,800) + 800, getRandom(1,600) + 800, 1, 1);
     public void update(Graphics g)
          if (ready)
               gfx.setColor(Color.black);
               gfx.fillRect (0, 0, this.getSize().width, this.getSize().height);
               //gfx.drawImage(starField,starFieldX,starFieldY,null);
               gfx.drawImage(playerShip,playerShipX,playerShipY,null);
               //gfx.drawString(Integer.toString(showFps),5,5);
               g.drawImage(buffer,0,0,null);
}

updated code, i cant get starField to be 1200px in height
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Alpha1 extends Canvas implements Runnable, MouseMotionListener, MouseListener, KeyListener {
     private Image buffer; //bufer image
     private Graphics gfx;
     private Graphics starFieldObj;
     private Image playerShip;
     private int frames = 60; //frames per second
     private MediaTracker mediaTracker; //tracks loaded images
     private boolean ready; //ready to  start animation
     private int [] keys = new int[256];
     private int playerShipX = 100;
     private int playerShipY = 100;
     private static Random random = new Random();
     private Image starField;
     private int starFieldSpeed = 5;
     private int starFieldX = 0;
     private int starFieldY = -600;
     public static void main(String[] args)
          Alpha1 t = new Alpha1();
          Frame f = new Frame("blah");
          f.setSize(800, 600);
          f.add(t, BorderLayout.CENTER);
          f.show();
          t.start();
          t.requestFocus();
          f.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent e){
                    System.exit(0);}});
     public Alpha1()
          addKeyListener(this);
          addMouseListener(this);
          ready = false;
          mediaTracker = new MediaTracker(this);
          playerShip = getToolkit().getImage("testship1.png");
          //starField = getToolkit().getImage("testbg.png");
          //mediaTracker.addImage(playerShip, 0);
          mediaTracker.addImage(starField, 0);
          try {
               mediaTracker.waitForID(0);
          catch (InterruptedException e) {
               e.printStackTrace();
     public void start()
          buffer = createImage(getSize().width,getSize().height);
          starField = createImage(getSize().width,1200);
          gfx = buffer.getGraphics();
          starFieldObj = starField.getGraphics();
          ready = true;
          new Thread(this).start();
     public void mouseDragged(MouseEvent e)     {}
     public void mouseMoved(MouseEvent e)     
          playerShipX = e.getX();
          playerShipY = e.getY();
     public void mouseReleased(MouseEvent e)     {}
     public void mousePressed(MouseEvent e)     {}
     public void mouseExited(MouseEvent e)     {}
     public void mouseEntered(MouseEvent e)  {}
     public void mouseClicked(MouseEvent e)     {}
     public void keyTyped(KeyEvent keyevent)     {}
     public void keyPressed(KeyEvent keyevent)
          keys[keyevent.getKeyCode()] = 1;
          System.out.println(keyevent.getKeyCode());
     public void keyReleased(KeyEvent keyevent)     
          keys[keyevent.getKeyCode()] = 0;
     public void run()
          generateStarfield();
          while (true)
               if (isVisible())
                    repaint();
                    updatePositions();
               }//end if
               try 
               { Thread.sleep(1000/frames); }
               catch (InterruptedException e)
               { e.printStackTrace(); }
          }//end while
     public void paint(Graphics g) {     /*empty etc*/ }
     public void updatePositions()
          if (keys[38] == 1 & keys[40] == 0) //IF UP IS PRESSED
          { playerShipY -= 3; }
          if (keys[40] == 1 & keys[38] == 0) //IF DOWN IS PRESSED
          { playerShipY += 6; }
          if (keys[37] == 1 & keys[39] == 0) //IF LEFT IS PRESSED
          { playerShipX -= 5; }
          if (keys[39] == 1 & keys[37] == 0) //IF RIGHT IS PRESSED
          { playerShipX += 5; }
          starFieldY = starFieldY + starFieldSpeed;
          if (starFieldY == 0)
               starFieldY = -600;
               System.out.println("dadssa");
     public int getRandom(int from, int to)
          if (from > to)
               int randTemp;
               randTemp = from;
               from = to;
               to = randTemp;
          return random.nextInt(to-from+1)+from;
     public void generateStarfield()
          starFieldObj.setColor(Color.black);
          starFieldObj.fillRect (0, 0, 800, 1200);
          for (int td=0; td < 900 ; td++) //draw 900x2 dots on 800x1200 image
                    starFieldObj.setColor(Color.white);
                    starFieldObj.fillRect (getRandom(1,800), getRandom(1,600), 1, 1);
                    starFieldObj.fillRect (getRandom(1,800) + 800, getRandom(1,600) + 800, 1, 1);
     public void update(Graphics g)
          if (ready)
               gfx.setColor(Color.black);
               //gfx.fillRect (0, 0, this.getSize().width, this.getSize().height);
               gfx.drawImage(starField,starFieldX,starFieldY,null);
               gfx.drawImage(playerShip,playerShipX,playerShipY,null);
               //gfx.drawString(Integer.toString(showFps),5,5);
               g.drawImage(buffer,0,0,null);
}

Similar Messages

  • Reading colour image using raster object and getsample() method

    Hello all,
    I am trying to read a grey image using this code below and it perfectly works:
    File filename = new File("myimage.jpg");
    BufferedImage inputimage = ImageIO.read(filename);
    Raster input = inputimage.getRaster();
    double pixelvalue = input.getSample(xx, yy, 0) ; // to read pixel colour.
    Now:
    what modifications should i do to read a colour image using getsample() method.
    any help, by example if y would.
    Thanks

    The code below
    double pixelvalue = input.getSample(xx, yy, 0) ; // to read pixel colour.actually doesn't obtain the pixel color. It reads a band of the specified pixel. If you are reading a tripple band image (24-bit colored image RGB ) then you have to invoke this method three times for band 0, 1 and 2. The arrangment of them depends on the BufferedImage type.
    In reply of your question, you can use getSamples method, refer to the java API documentation of the BufferedImage class for more info.
    you can also check methods getRGB and setRGB, they used to get/set the entire pixel in range of 0x00000000 to 0x00FFFFFF ( 0x00RRGGBB of image type TYPE_INT_RGB )
    Regards,
    Mohammed M Saleem

  • Drawing a String using Graphics Object

    When I am printing a long String using the following method
    String currentMessage // The size of the String is large
    g.drawString(currentMessage, x, y, Graphics.BOTTOM | Graphics.HCENTER);
    only the middle of the String is shown on the sreen.The first and last parts are stripped off because of the size of the screen.
    Anyone knows how to specify the size of the font, or how to force the string to continue on a new line if its size is bigger than the width of the screen?
    Cheers

    There is not native support for line wrapping in drawString().
    You can change the font by using g.setFont(),
    Create your on font, and specify the font size as small.
    The Font class includes a method to determine the length of a string. You can use this method to check the length of the String if the string is longer than the screen width, you can break the String into parts (substrings) and draw each of the parts.
    Alternatively, you can use this line wrapping class http://hostj2me.com/appdetails.html?id=6

  • Using graphics object in keyPressed

    hi,
    i'm extendig Canvas class in a ew class ad want to use the Graphics's object in the KeyPressed function.
    How can , i get the object in the same function.

    Instead of a relative path have you tried an absolute file path?
    In the CR Jupiter User Guide it states:
    http://technicalsupport.businessobjects.com/KanisaSupportSite/search.do?cmd=displayKC&docType=kc&externalId=xir2crusergdeenpdf&sliceId=&dialogID=9556855&stateId=1 0 9558242
    -     The JRC now supports dynamic locations for graphics.
    In the BOE XI R2 release notes it states:
    http://technicalsupport.businessobjects.com/KanisaSupportSite/search.do?cmd=displayKC&docType=kc&externalId=xir2windowsreleasenotesenpdf&sliceId=&dialogID=9556855&stateId=1 0 9558242
    -     The JRC fails to support reports that contain relative paths to dynamic images.
    So this will work if you use fully qualified path names.

  • How can I display the length of the yet unfinished line that a user is drawing in the image using the line tool of the IMAQ tool palette.

    Is this really not possible using standard Labview/Vision YI`s?

    Herbert,
    I can't find a way to extract the information you want within the program. However, this information is displayed as part of the IMAQ tool palette while the user is drawing the line. The pallette shows the anchor point, the X and Y offsets, and the line length and angle.
    Bruce
    Bruce Ammons
    Ammons Engineering

  • Placed image hides graphic objects on master

    Mac OS 10.8 \ ID CS5
    Rectangular frame created on master \ photo corners created in InDesign for each of the four corners
    In the document page when an image is placed in the frame, the image hides the portion of the corners that lie within the frame
    I tried bring to front for corners - no joy - can't seem to send frame to back
    I can copy the corners from the master page and paste in place on the document page - works fine - full corners show with image below
    With 50-75 anticipated pages and about 75 photos, I need a better way. Help, please?
    Message was edited by: FroggyGreen

    Make a new layer (above the current one).
    Go to your Master page and move the elements you want in front to the new layer.

  • Transparent Graphics Object

    Alright, I have one graphics object that draws all of the main elements of the screen, and I have a buffered image that is modified through a second graphics object. I want to know how to make the background for the second object transparent, so that if I drew something onto it, then drew the buffered image into the main graphics object, I'd be able to see all the drawing done in the original graphics object behind the uncovered areas, sort of like an overlay. Code examples are highly appreciated. Thanks in advance for any replies.
    (PS: Right now when I draw the image, it covers up the entire screen with the color grey, making it impossible to see the objects behind it.)

    I wrote example for AWT because in SWING it can be done very easy. Run this code, it runs fine. Use only your image files.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    public class ImageTest extends Canvas implements WindowListener {
    public static void main(String[] args) {
    Frame frame = new Frame("Image testing");
    ImageTest instance = new ImageTest();
    frame.add(instance);
    frame.addWindowListener(instance);
    frame.pack();
    frame.setVisible(true);
    public Dimension getPreferredSize() {
    return new Dimension(256, 256);
    BufferedImage backgroundImage;
    BufferedImage alphaImage;
    void initImage() {
    Image img = getToolkit().createImage("D:\\temp\\JavaTests\\viewcode.jpg");
    Image bkImage = getToolkit().createImage("D:\\temp\\JavaTests\\SolarEclipse.jpg");
    MediaTracker Mt = new MediaTracker(this);
    Mt.addImage(img, 0);
    Mt.addImage(bkImage, 1);
    try{
    Mt.waitForAll();
    }catch(Exception e){};
    BufferedImage bi = new BufferedImage(img.getWidth(this), img.getHeight(this), BufferedImage.TYPE_4BYTE_ABGR);
    alphaImage = new BufferedImage(bkImage.getWidth(this), bkImage.getHeight(this), BufferedImage.TYPE_4BYTE_ABGR);
    Graphics gr = bi.getGraphics();
    gr.drawImage(img, 0, 0, this);
    backgroundImage = (BufferedImage)bi;
    gr = alphaImage.getGraphics();
    gr.drawImage(bkImage, 0, 0, bkImage.getWidth(this)/2, bkImage.getHeight(this)/2, bkImage.getWidth(this)/2, bkImage.getHeight(this)/2, bkImage.getWidth(this), bkImage.getHeight(this), this);
    Color bl = new Color(0, 0, 0);
    for (int x=0; x<bkImage.getWidth(this); x++)
    for (int y=0; y<alphaImage.getHeight(this); y++) {
    Color c = new Color(alphaImage.getRGB(x,y));
    int r = c.getRed();//x*4;
    int g = c.getGreen();//y*4;
    int b = c.getBlue();//255 - (x+y)*2;//Math.abs(y*8-255);
    // Make transparent colors, which look like black
    int a = (r == b && g == b && r < 100 && g < 100 && b < 100)?0:255;
    int vv = (a<<24) | (r<<16) | (g<<8) | b;
    alphaImage.setRGB(x, y, vv);
    public void paint(Graphics gfx) {
    if (backgroundImage == null)
    initImage();
    gfx.drawImage(backgroundImage, 0, 0, this);
    int i = 0;
    int delta = 100;
    gfx.drawImage(alphaImage, i, i, this);
    gfx.drawImage(alphaImage, i + delta, i + delta, this);
    gfx.drawImage(alphaImage, i + delta*2, i + delta*2, this);
    gfx.drawImage(alphaImage, i + delta*3, i + delta*3, this);
    gfx.drawImage(alphaImage, i + delta*4, i + delta*4, this);
    gfx.drawImage(alphaImage, i + delta*5, i + delta*5, this);
    void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    public void windowActivated(java.awt.event.WindowEvent windowEvent) {
    public void windowClosed(java.awt.event.WindowEvent windowEvent) {
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
    System.exit(0);
    public void windowDeactivated(java.awt.event.WindowEvent windowEvent) {
    public void windowDeiconified(java.awt.event.WindowEvent windowEvent) {
    public void windowIconified(java.awt.event.WindowEvent windowEvent) {
    public void windowOpened(java.awt.event.WindowEvent windowEvent) {

  • Display byte array image or ole object in Section through dynamic code?

    To Start I am a Complete Newbe to Crystal Reports. I have taken over a project originally written in VS2003 asp.net using SQL Server 2005 and older version of Crytal Reports. I have moved project to VS2010 and Cryatal Reports 10 still using SQL Server 2005. Have multiple reports (14 to be exact) that display data currently being pulled from database suing a dataset, each report has from 4 to 14 Sections. I have modified database table with two new fields. Field1 contains string data with full path to a scanned document (pdf or jpeg). Field2 holds a byte array of the actual image of the scanned document. I have tested the database and it does infact contain the byte array and can display the image via VB.net code. I can make the report display the scanned image using ole object.
    Now my real question: I need to add a new Section and it should display either the byte array of the scanned image or the actual scanned image (pdf or jpeg) . How can I have it do either of these options via code dynamicly while application is running?

    First; only CRVS2010 is supported on VS2010. You can download CRVS2010 from here;
    SAP Crystal Reports, developer version for Microsoft Visual Studio: Updates & Runtime Downloads
    Developer Help files are here:
    Report Application Server .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_api_en.zip
    Report Application Server .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_dg_en.zip
    SAP Crystal Reports .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_api_2010_en.zip
    SAP Crystal Reports .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_dg_2010_en.zip
    To add the images, you have a number of options re. how to. You even have two SDKs that y ou can use (RAS and CR).
    Perhaps the best place to start is with KB [1296803 - How to add an image to a report using the Crystal Reports .NET InProc RAS SDK|http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_bi/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233393336333833303333%7D.do]. The KB describes how to add images to a report using the InProc RAS SDK, but also references other KBs that use CR SDK.
    Also, don't forget to use the search box in the top right corner of this web page.
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • How can I run graphic object on report. ( I got REP-1246 Chart not found)

    Hi All,
    I made a report that consists a chart object. When I run it on report builder, it works well. But When I call the report from client side, I got "Rep-1246 Char Document not found" . I tried to solve it , I couldn't solve the problem . If I delete chart object from report , then report works well on client side. I didn't use graphics builder to create graphs I used only report builder to do it. I read the threads about it , but I couldn't find the solution. All solutions are about path of graphic file. I don't understand it. Because I only have *.rdf *.rep file. There is no any graph file in my system. I can create it in graphic builder but I don't know how can I deploy the graph object into report layout and run ?
    I need urgent help ..
    Thanks in advice
    Suleyman

    Hi again , I used developer 2000. In order to show graphic object on report firstly
    I created my graphic object on oracle graph builder.After that I save it like mygraph.OGD . Then I added graphic object on report builder by using graphic object on report builder. When you click the graphic object you will see CHART FILENAME part in part of CHART. In this field , you should add graphic file path that you created on graphic builder. I added mygraph.OGD into this filename part. I worked well.
    Good LUck !

  • Graphics object under unix

    Hi
    I m using sun solaris and i want to create a graph using graphics object and then write on to jpg file. For the same i musing JPEGEncoder and able to do that sucessfully under win NT and also under solaris but only when that X windows is installed and that service is running.
    My concern is i want to do the above task where x windows is not installed , in such a case where will i get graphics object from and how will graph be plotted.
    Is there any work around without using 3rd party tool
    Please let me know

    look at this http://www.eteks.com/pja/en/

  • Best way to draw thousands of graphic objects on the screen

    Hello everybody, I'm wanting to develop a game where at times thousands of graphic objects are displayed on-screen. What better way to do this in terms of performance and speed?
    I have some options below. Do not know if the best way is included in these options.
    1 - Each graphical object is displayed on a MovieClip or Sprite.
    2 - There is a Bitmap that represents the game screen. All graphical objects that are displayed on screen have your images stored in BitmapData. Then the Bitmap that represents the game screen copies for themselves the BitmapData of graphical objects to be screened, using for this bitmapData.copyPixels (...) or BitmapData.draw  (...). The Bitmap that represents the screen is added to the stage via addChild (...).
    3 - The graphical objects that are displayed on screen will have their images drawn directly on stage or in a MovieClip/Sprite added to this stage by addChild (...). These objects are drawn using the methods of the Graphics class, as beginBitmapFill and beginFill.
    Recalling that the best way probably is not one of these 3 above.
    I really need this information to proceed with the creation of my game.
    Please do not be bothered with my English because I'm using Google translator.
    Thank you in advance any help.

    Thanks for the information kglad. =)
    Yes, my game will have many objects similar in appearance.
    Some other objects will use the same image stored, just in time to render these objects is that some effects (such as changing the colors) will be applied in different ways. But the picture for them all is the same.
    Using the second option, ie, BitmapDatas, which of these two methods would be more efficient? copyPixels or draw?
    Thank you in advance any help. =D

  • Image in a Graphics object

    Hi, I'm dealing with the Batik API for working with svg images, but I need to do some wmf imager representation too.
    This API offers a class which is able to read WMF files, giving a "WMFRecordStore", that you can use to initialize a "WMFPainter".
    Anyway, this WMFPainter class has a "paint" method which I hoped that I could use to print the wmf info in the screen but... I don't know if it can be done.
    You must pass a Graphics object to the "paint" method.
    If I want to add an image to a JLabel, as I'd do with an ImageIcon, do I have to get the current JLabel Graphics object? Will the image keep displayed when repainting? Is this a correct way of doing this?
    thanks a lot

    if you have to paint special things on a component, you have to subclass the component and override the paint (or paintComponent) method. You don't want to be getting the graphics object from a component and draw on it, it's not going to work properly.

  • How to use a Graphics Object in a JSP?

    Hello, I do not know if this is a good or a silly question. Can anyone tell me if we can use a Graphics object in a JSP. For example to draw a line or other graphics, i am planning to use the JSP. Any help is much appreciated.
    Regards,
    Navin Pathuru.

    Hi Rob or Jennifer, could you pour some light here.
    I have not done a lot of research for this, but what i want to do is below the polygon i would like to display another image object like a chart... is it possible? If so how to do it? Any help is much appreciated.
    here is the code:
    <%
    // Create image
    int width=200, height=200;
    BufferedImage image = new BufferedImage(width,
    height, BufferedImage.TYPE_INT_RGB);
    // Get drawing context
    Graphics g = image.getGraphics();
    // Fill background
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    // Create random polygon
    Polygon poly = new Polygon();
    Random random = new Random();
    for (int i=0; i < 5; i++) {
    poly.addPoint(random.nextInt(width),
    random.nextInt(height));
    // Fill polygon
    g.setColor(Color.cyan);
    g.fillPolygon(poly);
    // Dispose context
    g.dispose();
    // Send back image
    ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(image);
    %>
    Regards,
    Navin Pathuru

  • Drawing a Graphics object on a Graphics object

    Is there anyway to draw a Graphics object on another Graphics object? I'm trying to show 2 screens, side by side, on a Canvas and I'm trying to cheat a little :-P Basically, I want to take half of one screen and half of another and put them on top of each other to form one screen.
    OR is there a way to turn a Graphics object into an Image object?

    I'm not sure if this is what you're after, but you can
    - create an offscreen image using "createImage(int width, int height)" method of a Component , then
    - obtain the graphics context of the offscreen image using "getGraphics()",
    - you can then draw onto the offscreen image using the graphics context.
    hope that helps. =)

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

Maybe you are looking for