Using image as background of frame

I have a JFrame. I want to add an image (created from a jpeg file) on it as a background. Then, I will draw on that background.
Please tell me how can I do.
I tried to use createImage method from JFrame object
image = frame.createImage(440,400);
and then create image from file
image2 = Toolkit.getDefaultToolkit().getImage(filename);
Graphics g = image.getGraphics();
g.drawImage(image2,0,0,null);
I intend to draw some elements on "image" after that. However, the image doesn't not appear on the frame right at the beginning.
Please help me.
Thanks.

I didn't realize that what I wanted was double buffering and even JPanel supports double buffering. However, I still have a problem.
Please take a look at my code below.
public class MyFrame extends JFrame {
    static ImagePanel panel;
    static Image backgroundImage;
    public MyFrame(){
     super("Simulation Program");
    public static void main(String[] args){
        MyFrame frame = new MyFrame();
        frame.setVisible(true);
     backgroundImage = Toolkit.getDefaultToolkit().getImage("background.jpg");
     panel = new ImagePanel();
     getContentPane().add(panel);
        drawOnPanel();
    public void drawOnPanel(){
     Graphics g = panel.pic.getGraphics();
     g.drawImage(backgroundImage,0,0,panel); //does not work!
     g.drawRect(0,0,50,50);//works well
     panel.repaint();
class ImagePanel extends JPanel {
    boolean firstPaint = true;
    Image pic;
    public void paint(Graphics g) {
          if (firstPaint){
               pic = createImage(440,400);
          firstPaint = false;
          g.drawImage(pic,0,0,this); //redraw the image
}My problem is that method drawImage I use to draw the background image on the panel doesn't work. I don't know why.
If I assign the image to pic member of ImagePanel as such:
       pic = backgroundImage;instead of pic = createImage(x,y); the background image appears.
However, if I do that, I cannot call this following method in drawOnPanel():
      g = panel.pic.getGraphics();because it is said that "You may call getGraphics() only with offscreen image". Then, I cannot add more graphics on the background.
Thanks for your time.

Similar Messages

  • Using image as background

    hi,
    I'm having a little problem, I don't think it's very difficult but the search on this forum is down a.t.m.
    Therefore I'm hoping you guys can help :-)
    Like the title already discribes i want to use an Image as background of a JPanel (or on another Frame if it isn't possible on this one) and still be able to put JLabels, JTextfields, etc. on the JPanel with a LayoutManager.
    To show what i mean:
    -->i want to do something similar to this code
    JPanel test=new JPanel(new BorderLayout()));
    test.setBackground(Color.WHITE);
    --->but instead of setting a Color as Background i want to set an Image :)
    greetings

    The search facility may be down, but you are searching the wrong forum anyway. This is a Swing question and should be posted in the Swing forum.
    But since you made the effort to search, here is a simple example:
    ImageIcon icon = new ImageIcon("???.jpg");
    JPanel panel = new JPanel()
         public void paintComponent(Graphics g)
              //  Dispaly image at at full size
              g.drawImage(icon.getImage(), 0, 0, null);
              super.paintComponent(g);
    panel.setOpaque( false );

  • Using image as background to Swing JPanel

    Hi,
    Have been trying to set background of JPanel to an image but cannot get it to work.
    Any ideas why not?! Here is the code Ive written:
    public Simple_Gui()
    //add the title for the frame
    super("Simple frame");
    this.getContentPane().setLayout(new FlowLayout());
    //add a window listener to close the window when the button is pressed
    this.addWindowListener(new WindowAdapter()
         public void windowClosing(WindowEvent we)     
              System.exit(0);
    //need a pane to hold the background image and buttons
         pane = createPanel();
    //this is the background image for the app to make it look lurrrvely
    ImageIcon imageIcon = new ImageIcon( "C://SDF_image.jpg" );
    //set the size of the Panel to the size of our image
    paneHeight = imageIcon.getIconHeight();
    paneWidth = imageIcon.getIconWidth();
    pane.setSize(paneWidth, paneHeight);
    //add the pane to the JFRAME so that it is visible
    this.getContentPane().add(BorderLayout.CENTER, pane);
    this.setVisible(true);
         public static JPanel createPanel()
              JPanel panel = new JPanel()
                   public void paintComponent(Graphics g)
              ImageIcon img = new ImageIcon("C://SDF_image.jpg");               Image image = img.getImage();
                   g.drawImage(image, 0, 0, this);                         super.paintComponent(g);                              }
              panel.setOpaque(false);
              panel.setLayout(new GridLayout(20, 4, 10, 10));
              panel.setVisible(true);
              return panel;
              public static void main(String[] args)
                   Smarty_Gui gui = new Smarty_Gui();
    Sorry about the indentation and format

    Something like this ...
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class UsingImageBackground extends JFrame {
    JPanel panel;
    JButton button = new JButton("OK!");
         public UsingImageBackground() {
       Container c = getContentPane();
         panel = new JPanel() {
              public void paintComponent(Graphics g)     {
                   ImageIcon img = new ImageIcon("new.jpg");
                   g.drawImage(img.getImage(), 0, 0, null);
                   super.paintComponent(g);
         panel.setOpaque(false);
         panel.add(button);
       c.add(panel);
         public static void main(String [] args){
              UsingImageBackground frame = new UsingImageBackground();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(160, 120);
              frame.setVisible(true);
    }

  • Framing image with transparent background png frame

    hi,
    i'm trying to find a way to frame images with transparent background png frames...
    what i'm doing now is
    1-drawing my image on a panel
    2-creating a 2nd image using the frame's filename, stretching this 'frame-image' to a size slighlty larger than that of my main image and drawing the 'frame-image'
    the problems with this method are:
    1-depending on the width of the frame, the frame sometimes hides parts of the image (thick frame), and sometimes there is a gap between the frame and the image (thin frame).
    2-if the image file containing the frame is larger than the frame (Ex: The image is 300x300, the frame is centered in this image and is 200x200; as opposed to the image is 200x200 and the frame takes up all the space), when i position the 'frame-image' near the top left corner of the image i want to frame, the frame appears at the wrong place (shifted down and to the right). This is due to the fact that i'm placing the top corner of the created 'frame-image' and not the frame, who is not in the top corner of my 'frame-image'.
    Is there a way to do what i'm trying to do???
    My ideas (which i don't know how to achieve are)
    1-To 'analyse' my transparent background png file and
         1-only keep the frame,
         2-calculate the frame's thickness
    OR
    2-Let java do the analyzing for me and tell it to frame my image with the frame in the png file
    please feel free to ask for more explanations if my description/question is confusing,
    thanks.

    Have you looked into the Border interface? If what you really want to do
    is put a custom border on a component, you may be able to do it this way.
    Anyway, here is some code that stacks and centres 2 images. It's not hard to do.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class Example extends JComponent {
        private BufferedImage backgroundImage;
        private BufferedImage foregroundImage;
        public Example(BufferedImage backgroundImage, BufferedImage foregroundImage) {
            this.backgroundImage = backgroundImage;
            this.foregroundImage = foregroundImage;
        public Dimension getPreferredSize() {
            int w = backgroundImage.getWidth();
            int h = backgroundImage.getHeight();
            return new Dimension(w, h); //assuming this is bigger
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            //paint both, centred
            int x0 = (w-backgroundImage.getWidth())/2, y0 = (h-backgroundImage.getHeight())/2;
            g.drawImage(backgroundImage, x0, y0, null);
            int x1 = (w-foregroundImage.getWidth())/2, y1 = (h-foregroundImage.getHeight())/2;
            g.drawImage(foregroundImage, x1, y1, null);
        public static void main(String[] args) throws IOException {
            URL url1 = new URL("http://weblogs.java.net/jag/Image54-large.jpeg");
            URL url2 = new URL("http://weblogs.java.net/jag/DukeSaltimbanqueSmall.jpeg");
            JComponent comp = new Example(ImageIO.read(url1), ImageIO.read(url2));
            final JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(comp);
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • How can I use an image as background for the entire page?

    With CSS mill, the solid color was defined in the color.X.property file and there is no place to define an image to use as the background? Is it doable to use an image as the background for teh entire page? If so, where to add it and how to implement? Thank you!
    Hao Pan ([email protected])

    While I have been able to add the image to a JLabel and insert it into frames, so that it looks like a suitable background, I have found it impossible to place any other component over the top of said imageDid you set a layout manager for the label?
    Check out the [Background Panel|http://www.camick.com/java/blog.html?name=background-panel] for two different solutions depending on your exact requirement.

  • Best Practice for Image placement and Anchored Frames for use in Robohelp 9

    Hi,
    I'm looking for the best practices in how to layout my images in Framemaker 10 so that they translate correctly to Robohelp 9.  I currently have images inside of Anchored frames that "Run into" the right side of my text. I've adjusted the size of the anchored frame so that my text flows correctly around the image. Everything looks good in Framemaker! Yeah! The problem is that when I link my Framemaker document to Robohelp, the text does not flow around my image in the same manner. On a couple of Robohelp screens the image is running into the footer. I'm wondering if I should be using tables in Framemaker in order to get the page layout that I'm looking for. Also, I went back and forth...is this a Framemaker question or is this a Robohelp question. Any assistance would be greatly appreciated.

    I think Jeff is meaning this section of the RoboHelp forums:
    http://forums.adobe.com/community/robohelp/robohelp_framemaker

  • How can I make an image tile length of browser without using it as background image?

    I understand that if you use the rectangle tool and stretch it to the edge of the page, triggerring the red margin, the tiled image is supposed to stretch the length of the browser. Although this works for width, tiling horizontally, for some reason, it doesn't work for length, tiling vertically. When I preview my work in browser, the tiled image doesn't extend along with the footer as I scroll down the page.
    When I use the image as background fill and tile it, then it works, but I need to use a different image for the background.

    Hi
    As you have mentioned you can either use browser fill with tile fitting or design the browser background image outside of Muse using any image editor like Photoshop and then use as browser fill which would include both images the one you want to use as background image and the one that you want to use as Tile on page section.
    Thanks,
    Sanjit

  • Using images with transparent backgrounds

    Hello. I'm trying to design several forms using a large background graphic along with several other overlays (defined by the form user) that contain transparent backgrounds. Unfortunately, everytime I go to change the graphic, the program won't recognize the transparency of the overlay and substitutes white in it's place. So, for example, I have a background image that is rectangular and when my form user selects an overlay that is circular, it inserts the circle with a white background (which is supposed to be transparent). Can anyone help me with this?
    Thanks!
    -Mike

    Min required version of flash player for my application is 9..
    I think I figured it out, Here is my solution:
    private function completeHandler(evt:Event):void
       var originalWidth:int=loaderG.content.width;
       var originalHeight:int=loaderG.content.height;
       var scale:Number = 0.5;
       var matrix:Matrix = new Matrix();
       matrix.scale(scale, scale);
       myBitmapDataObj=new BitmapData(originalWidth, originalHeight, true, 0xFFFFFF);
       myBitmapDataObj.draw(loaderG.content, null, null, null, null, true);
       var copyBitmapData:BitmapData= new BitmapData(originalWidth* scale, originalHeight* scale, true, 0x000000);
       copyBitmapData.draw(myBitmapDataObj, matrix, null, null, null, true);
       var myBitmapG:Bitmap=new Bitmap(copyBitmapData,PixelSnapping.AUTO,true);
       addChild(myBitmapG);
    I also try blur filter on my bitmap:
    var blur:BlurFilter = new BlurFilter();
       blur.blurX = 1.4;
       blur.blurY = 1.4;
       blur.quality = BitmapFilterQuality.HIGH;
       myBitmapG.filters = [blur];
    Or is there better solution?

  • Using "Image/Transform/Perspective" on a layer?

    Hi,
    I'm new at this.  I have a shot of a big room with empty art frames on the walls.  I have rectangular layers that are shots of paintings that I want to drop into the frames, but of course the paintings layers have to be skewed to show the perspective angle (trapezoid) that matches the room.  Problem is, it seems that I can only use Image/transform/perspective on the painting files before they become layers.  This means guessing the perspective, then moving them into the background, which is trial&error at best.  It's very hard to guess the appropriate perspective when the file isn't a layer. It seems that once the painting files become layers, the "perspective" option is no longer available.  I can use "skew," or "free transform," but not "perspective."    "Skew" doesn't work, because while it will allow changing the rectangle into a paralellogram, it won't allow me to change the rectangle into a trapezoid. "Free Transform" doesn't work for the same reason.  So, How do you apply the "perspective" function to a layer?
    If I knew how to change the rectangle by grabbing one of a selection's corner anchor boxes and fixing it place, that would help because I could create my own trapezoid, but I don't know how to do that.  Does anyone?
    Thanks!

    I've no idea why all the transform options aren't available; they are here.
    Anyway, try this:
    Drag or copy/paste the painting in. It will come in as a new layer.
    Convert that layer to a smart object (Layer > Smart Object > Convert..). Reduce the smart object opacity to 50%.
    Choose Transform > Distort and move the corners individually into place.
    When you're happy, set opacity back to 100% and rasterize the smart object.
    The beauty of the smart object in this case is that you can transform repeatedly without any additional quality loss; it will be rendered only once when you rasterize.

  • IndesingCS2 server scriptable pluign: how to import image file into a frame.?

    Hello<br />I am creating a scriptable pluign for indesingcs2 server.<br />Now I am stuck at importing a image file in a image frame on a document.<br />The code which was running fine for indesingcs2 desktop is given below.<br />/////////////////////////////////////////////////////////////////////////////////////// ///////////<br />     IDFile sysFile = SDKUtilities::PMStringToSysFile(const_cast<PMString* >(&ImageFileNamewithcompletepath));     <br />     InterfacePtr<ICommand> importCmd(CmdUtils::CreateCommand(kImportAndLoadPlaceGunCmdBoss));<br />     if(!importCmd) <br />          return kFalse;          <br />InterfacePtr<IImportFileCmdData> importFileCmdData(importCmd, IID_IIMPORTFILECMDDATA); <br />     if(!importFileCmdData)<br />          return kFalse;<br /><br />     <br /><br />     //db is input.I got it using the techniques mentioned in the indesign-server-plugin-techniques.pdf<br />     //page 18..<br />     importFileCmdData->Set(db, sysFile, kMinimalUI);<br />     ErrorCode err = CmdUtils::ProcessCommand(importCmd);<br />     if(err != kSuccess) <br />          return kFalse;<br /><br />     InterfacePtr<IPlaceGun> placeGun(db, db->GetRootUID(), UseDefaultIID());<br />     if(!placeGun)<br />          return kFalse;<br /><br />     <br />     UIDRef placedItem(db, placeGun->GetItemUID());<br /><br />     InterfacePtr<ICommand> replaceCmd(CmdUtils::CreateCommand(kReplaceCmdBoss));<br />     if (replaceCmd == nil)<br />          return kFalse;<br /><br />     InterfacePtr<IReplaceCmdData>iRepData(replaceCmd, IID_IREPLACECMDDATA);<br />     if(!iRepData)<br />          return kFalse;<br />     <br />     iRepData->Set(db, imageBox.GetUID(), placedItem.GetUID(), kFalse);<br /><br />     ErrorCode status = CmdUtils::ProcessCommand(replaceCmd);<br />     if(status==kFailure)<br />          return kFalse;<br /><br />     return kTrue;<br />/////////////////////////////////////////////////////////////////////////////////////// //////////<br />I used the same code for making scriptable plugin for indesignCS2 server as it doesn't involve use of any UI element.<br />But this code is not working.It doesn't crash or returns kFalse.<br />What i see after executing the plugin through script is a grey region for image in the graphics frame.<br /><br />I request if anyone gives me solution to this i will be highly grateful to him.<br /><br />Thanks and Regards,<br />Yogesh Joshi

    Actually, your code is working fine, as there are no returned errors, asserts or crashes.
    The reason you are just seeing a gray box, is that the display performance is set to the lowest level in InDesign Server for performance reasons.
    Hint: Open the document in "desktop" InDesign, right click on the image, and look at the Display Performance settings for the image.
    See
    Ken Sadahiro, "[CS2 Server] Controlling display performance, how?" #1, 23 Feb 2006 8:01 am
    You can of course programmatically change it to the normal or high res settings from within your plug-in, but it might slow down the performance of InDesign Server a bit.
    One additional comment:
    In your code where you do this:
    importFileCmdData->Set(db, sysFile, kMinimalUI);
    I would do this, just to be safe:
    if (LocaleSetting::GetLocale().IsProductFS(kInDesignServerProductFS )) { importFileCmdData->Set(db, sysFile, kSuppressUI); } else { importFileCmdData->Set(db, sysFile, kMinimalUI); }

  • How do you make an image a background image if the menu option is dimmed?

    I'm using the Cork Board template in a Pages layout document. I wanted to use the cork background in another page. Option dragging the cork image creates a copy in the new page. I can "Send it to back" but the Arrange->Send Object to Background command is dimmed. The problem is that "Send it to back" does not put it behind the header or footer so my page numbers are not visible.
    Oddly, if I just drag the cork image from one page to another, it remains a background object in the new page. Copying it causes it to come out of the background.
    Anybody have an idea why the Send Object to Background command is dimmed?

    In fact, my guess is that the cork.pdf object is a background object because it is a template transferred from Pages '06 to Pages '08.
    During the conversion, some properties are passed even if they aren't treated by the new version.
    If some one wish to let some of these items in the true background, as far as I know, the only available soluce is:
    create a new object from the delivered template
    unlock some items if necessary
    remove useless items
    lock back the kept item
    save the document as a template.
    Never change the background property of the kept items.
    As far as an item is a "true background" one,
    trying to move an other item to the background will leave it above the "true background object".
    Yvan KOENIG (from FRANCE mardi 9 septembre 2008 15:49:21)

  • Uneven color between background text frame and underlying frame fill

    Hi. I'm using InDesign CS3 on Windows XP.
    On my document, the main heading is in a frame with a fill of 'None'. The heading text has a bevel and emboss. The text frame sits on a background A4 frame which is filled with a Pantone spot colour.
    When I print the cover page, the color filling the text frame is slightly different from the background Pantone color, even though the text frame has no color fill.
    When I checked the document before printing in View>Overprint Preview, it appeared to be fine. The PDF also looked fine. In both situations, I could not discern a color difference but it is there in the printed document.
    To provide a color behind the text which matches the fill color of the frame occupying the whole page, what should I do? My gut feel is to select the background frame and the text frame and check the knockout box on the effects panel or something like that.
    I hope I have explained sufficiently clearly the problem I am experiencing.
    Look forward to hearing your suggestions.
    Thanks
    Frank

    http://indesignsecrets.com/eliminating-ydb-yucky-discolored-box-syndrome.php

  • Anchored images outside of button frame

    Hi Experts
    I am trying to find a way of getting an image to become visible on rollover on a button I've created, without having the image positioned within the button frame. The images are large & I have several small buttons on the page, each linked to text frames with anchored text objects (the images.) Anchoring the images outside the text frame is no problem, but visibility is limited to the button frame.How do I link large images to small buttons that only activate on rollover? Any ideas? PLEASE help!

    Convert that image you want to appear to separate button, and attach show/hide buttons action to your real button. Use rollover as trigger for showing your image, and rollout for hiding it again....

  • InDesign CS3 Scripting XML Import Multiple Images into same Text Frame

    I am having trouble importing multiple images into the same Text Frame using XML import. I imported 5 images into the text frame. However, all 5 images are laying on top of one another. Does anyone know if there is a way to have all images laying out like how Microsoft Word handles inline images, i.e., laying out next image to the right of previsous image in the same line and if there is not enough space left in the line, then wrap to next line. Thanks in advance. I understand I could use JavaScript to do post import processing, e.g, calculate the image size and place each images accordingly. But I am trying to see whether there is a way to do this without scripts.

    You can apply an object style to all anchored images by script. A text frame containing main flow should be selected.
    var doc = app.activeDocument;
    var textFrame =  app.selection[0];
    var rectangles = textFrame.texts[0].rectangles;
    if (rectangles.length > 0) {
         for (var i=0; i < rectangles.length; i++) {
              rectangles[i].appliedObjectStyle = doc.objectStyles.item("Cover");
    However, there is a better approach:
    Step 1
    Create place holders for a single "Book" element and format it as needed -- apply an object style to the cover.
    Step 2
    Import the xml file -- the placeholders are replaced with data from the 1st xml element
    Step 3
    Drag & drop the element containing all "Books" elements into the main flow -- all elements are placed and formatted the same way as in step 1.
    Finally, add a new page, click the overset text icon and autoflow text to add pages so that to fit all the text.
    Hope this helps.
    Kasyan

  • Using images with Transparency in Photobooks

    I'm to a point where I would like to use images that utilize transparency in Aperture photo books. Is this possible? So far, PSD files that I've cropped with PS's lasso tools to have transparent areas surrounding their subject tend to change this area to white when dropped into a book.
    Does anyone know of a way or format to use to retain this transparency? I love the speed of Aperture's photobook tools, along with export and printing options, and would like to be able to layer images that bleed together, or have a cut-out subject on top of others, but I haven't noticed a way as of yet.
    Is this ability even available in Aperture yet?
    If not, is there a third party plugin that gives it to the user when making photo books?
    Please let me know soon, else i'm going to have to adjust my workflow back to photoshop only for page set layouts and the created PSD files on blank book pages- not fun.

    i have been trying different ways to make it work fine, and find several things to consider:
    Note: for the next ways i tried with images with transparency.
    1 searching images in the iPad with safari and saving it into Photo app
    then copying it with the popup and pasting it with the popup inside Pages or Keynote:
    work fine.
    2 using the saved images that worked fine in the first way but
    then inside Pages in my opened document, using the menu to import the image from the
    Photo app, to insert the same downloaded image used in the first case:
    does not work, the image appears with a white background.
    3 trying the first way (manually copying and pasting) but with the images i imported from
    my MacBook Pro using the normal way via iTunes(10.1.1 (4))
    does not work, some images appears with a black background, other images
    appears with a white background.
    4 trying with the images of the third way, but changing the method using the photo app
    menu from Pages
    does not work as in the third way
    i dont have problem using transparency images in the first complex way.
    my problem is when i try to use images with transparency in the other three normal ways.

Maybe you are looking for

  • Crystal Report and SAP BW Query

    I have developed the Crsytal Report (ontop of SAP BW Query), and save this report into my local c:\ drive. Now I made some changes to the BW Query (this is the Datasource of my Crystal Report) to include new Key Figure and Characteristic via BEx Quer

  • Lost in the workspace drop down the "show full menu's" CS5 Indd

    and yes i went to edit menu's and the visiblity isnt even an option- is there a solution for this- thansk in advance...

  • I am unable to change my Country to UK. For some reason it keeps coming up that I am from canada??

    I am trying to buy the personal year plan but I am unable to as the price keeps coming up as dollars. When I went to look, I realised that I have been set to being from Canada and am unable to change it please help.

  • Import Slide Show

    I created a slide show in iPhoto 9.1.5 and exported it to QuickTime. The .mov is 8.2 meg residing on my desktop. I imported it to FCE. I created a new sequence, in an existing project, and double clicked the sequence. The sequence appeared in the tim

  • ORA-02097,ORA-00384 error

    I want to use db_recycle_cache_size,I find the size of db_recycle_cache_size is 0,like follows: SQL> show parameter db_recycle_cache_size NAME TYPE VALUE db_recycle_cache_size big integer 0 Then I use alter system command to resize db_recycle_cache_s