How to draw an image on transparent JPanel?

I want to draw an image on the transparent JPanel. How to do it?
I do like this:
( In constructor )
setOpaque(false);
String imageName = "coral.jpg";
iimage_Bg = Toolkit.getDefaultToolkit().getImage(imageName);
( In paintComponent( Graphics g ) )
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage( iimage_Bg, 0, 0, getWidth() , getHeight() , Color.white, null );
But it doesn't work. Please help me!
Thank you very much.
coral9527

Check the values that are returned from getWidth() and getHeight(). If they either are zero, then paintComponent(Graphics g) never gets called by the components paint(Graphics g) method. I cannot see the how this component has been added or displayed so can give no advice on how you can guarantee getting a valid size. If you have simply added it to a JFrame and called pack(), the size will be zero, as the panel does not contain any components (you would not have this problem if you were adding a JLabel with an ImageIcon for example). Try not packing the frame, and giving it a valid size.

Similar Messages

  • How to draw an Image on a JPanel?

    Hi all,
    Can any one give code for drawing an image on a JPanel?
    thanks,
    amar

    That's for the JLabel right? ... For a JPanel on a JFrame, you could do something like this:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.net.URL;
    public class TestImagePaint  extends JFrame {
      private BjPanel bjp;
      public TestImagePaint( String imageName )   throws IllegalArgumentException {
        if ( imageName == null  ||  !( new File( imageName ).isFile() ) ) {
          throw new IllegalArgumentException( "\nIn TestImagePaint constuctor"
                                             +"\t IllegalArgumentException:" );
        bjp = new BjPanel( imageName );
        getContentPane().add( bjp );
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setBounds( 100, 100, 400, 300 );
        setVisible( true );
      public static void main( String[] argv ) {
        new TestImagePaint( argv[0] );
      public class BjPanel  extends JPanel {
        private URL   url;
        private Image image;
        public BjPanel( String imageName ) {
          try {
            url   = BjPanel.class.getResource( imageName );
            image = Toolkit.getDefaultToolkit().getImage( url );
            repaint();
          catch( Exception e ) {
            System.out.println( "Can't get Image: "+imageName+"\n\t"+e );
            System.exit( -1 );
        public void paint(Graphics g) {
          g.drawImage( image, 0, 0, this );
    }

  • How do I draw an image on a JPanel?

    To be honest I have no idea even where to start. I tried hacking through the tutorials but it just didn't help me (normally they do, I don't what's up).
    Anyway, so what I'm trying to do is build a game. The Graphics2D is great for simple shapes but drawing characters is getting kind of ridiculous (tedious + difficult + looks bad). So, I need to figure out how to display an image on a JPanel.
    To that end I have several questions.
    1 - What image type do I use? Like jpeg, bmp, gif, etc.
    2 - How do I make parts of it transparent?
    3 - How do I make it appear on the screen, given some coordinates on the JPanel?

    To draw an image directly to a JPanel given certain coordinates, you have to create a custom JPanel and override its paintComponent() method. Like this:
    class PaintPanel extends JPanel{
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    //painting code goes here}
    }Java can load in and draw GIF and JPEG images. If you decide to use GIF files, any good image editor like Adobe Photoshop should be able to make them transparent for you before the fact. If you want to set transparency within your java program you will have to create a BufferedImage and make certain colors within it transparent, but I would like to know how to do that as much as you do.

  • How to add an image to a JPanel ?

    hi,
    do you now how to add an image to a JPanel ?
    thanks a lot !

    You can either use the Graphics method drawImage from the panel's paintComponent(Graphics g) method, or you can create an ImageIcon, with your Image in its constructor. And then create a JLabel, passing that ImageIcon in its constructor. Then, you can simple use the panel.add() method to add that JLabel.
    For using the paintComponent method, check out the thread already posted above (I'll type it in again just in case)
    http://forum.java.sun.com/thread.jsp?forum=31&thread=288769
    If you want to use a JLabel, you can do something like this:
    Image img;
    JLabel label = new JLabel(new ImageIcon(img));
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    panel.add(label);Val

  • How to add an image in a JPanel

    Hi All,
    How to add an image in a JPanel and make it display.
    Thanks,

    I have tried with the below code. If I there is any fault please correct me.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class HomePage extends JFrame implements     ActionListener {
        JButton cmdClick;
        JLabel label;
        JPanel homePanel = new JPanel();
        JPanel headPanel = new JPanel();
        JPanel btPanel = new JPanel();
        private JPanel mainPanel = new JPanel(new CardLayout());
        CardLayout cl;
        CalScenario calcFrame = null;
        public HomePage() {
           setTitle("Test Kit");
           setSize( 1008,399);
           setBackground( Color.gray );
           setResizable(false);
           Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
           Rectangle window = getBounds();
           setLocation((screen.width - window.width) / 2, (screen.height - window.height) / 2);
           setVisible(true);
            homePanel.setLayout(new BorderLayout());
            headPanel.setPreferredSize(new Dimension(1008,153));
            label = new JLabel("Main menu");
            headPanel.add(label);
            headPanel.setBackground(Color.CYAN);
            ImageIcon icon = new ImageIcon("images/slash.gif");
            JLabel imglabel = new JLabel();
            imglabel.setIcon(icon);
            headPanel.add(label);
            this.getContentPane().add(headPanel);
            btPanel.setBackground(Color.ORANGE);
            cmdClick = new JButton("Click here");
            btPanel.add(cmdClick);
            cmdClick.addActionListener(this);
            homePanel.add("North",headPanel);
            homePanel.add("West",btPanel);
            calcFrame = new CalScenario(mainPanel);
            mainPanel.add(homePanel, "HomePanel");
            mainPanel.add(calcFrame, "CalcFrame");
            cl = (CardLayout) (mainPanel.getLayout());
            add(mainPanel);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void actionPerformed(ActionEvent source)  {
          if (source.getSource() == (JButton) cmdClick) {
                cl.show(mainPanel, "CalcFrame");
        public static void main( String args[]) {
             HomePage homeFrame = new HomePage();
             homeFrame.setVisible(true);
    }

  • How to draw an image at the center of a JscrollPane

    I have an image that I want to be centered in my JScrollPane. When I zoom-in, I want the image to fill the entire jscrollpane. When I zoom out it returns to the original scale. My problem is, when I open the image, it appears at the upper left corner of the JScrollPane. I want it centered. Also, when I zoom-in, it gets larger than the scrollpane. That is it goes beyond the boundaries of the JScrollpane. The function I am using to draw the image is:
    Image img = imp.getImage();
                   if (img!=null)
                        g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
                        srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);If I change the initial x,y values from (0,0) to any other value, it grays the upper left corner. So forinstance, if I did the following, the upper left corner of the scrollpane would become gray.
    g.drawImage(img,100,200, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
                        srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height,null);How can I center my image in the scrollpane?

    When I zoom-in, I want the image to fill the entire jscrollpane. When I zoom out it returns to the original scaleSo why are you using a scroll pane? A scroll pane is used when its contents can potentially be larger than the scrollpane.
    Although it wasn't originally designed for this purpose you can probably use my [Background Panel|http://www.camick.com/java/blog.html?name=background-panel]. It supports displaying an image at its actual size as well as scaled to fit the panel. So you should just be able to toggle the style as required.

  • How can I draw a image in transparent mode

    I write a applet which derived from JApplet. I want to draw a icon on It's content panel transparently, but it seems that ImageIcon can't handle *.ico.
    What should I do?

    It's solved.
    .gif can do this thing.

  • How to draw a 3Drect in a JPanel.

    Hi, I'd like to draw a 3D rectangle in a panal to make some components looks grouped. e.g. if I have a name(JLabel: JTextField) and address(JLabel:JTextField) in a panel and want to draw a 3D rectangle around these two fields, how can I do that? Looks that the paint(Graphics g) doesn't work here.
    The following is my test program, it has two files, an applet as program entrance and a Panel to draw on:
    // TestApplet.java
    import javax.swing.*;
    public class TestApplet extends JApplet     {
         public void init()     {
              TopPanel tp = new TopPanel();
              add(tp);
    // TopPanel.java
    import javax.swing.*;
    public class TopPanel extends JPanel     {
         public TopPanel()     {
              JLabel lb = new JLabel("test");
              add(lb);
              Choice c = new Choice();
              c.add("1");
              c.add("2");
              add(c);
         public void paint(Graphics g)     {
              g.draw3DRect(5, 5, 40, 40, false);
              super.paint(g);
    }

    sorry for the messy code.
    I've tried switching the two lines, but it doesn't
    work. :(
    Here is the repost of the code, I don't know why I
    can't edit the original post....
    // TestApplet.java
    import javax.swing.*;
    public class TestApplet extends JApplet     {
         public void init()     {
              TopPanel tp = new TopPanel();
              add(tp);
    // TopPanel.java
    import javax.swing.*;
    import java.awt.*;
    public class TopPanel extends JPanel     {
         public TopPanel()     {
              JLabel lb = new JLabel("test");
              add(lb);
              Choice c = new Choice();
              c.add("1");
              c.add("2");
              add(c);
         public void paint(Graphics g)     {
              super.paint(g);
              g.draw3DRect(5, 5, 40, 40, false);
    1. You can only edit posts that have not been replied to.
    2. Your code worked for me? (What is the problem).
    3. Suggestions use a JComboBox instead of Choice. (It is not good to mix AWT and Swing.) Also you should be overiding paintComponentinstead of paint.
              @Override
              public void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   g.draw3DRect(5, 5, 40, 40, false);
              }

  • How to draw an Image on a BufferedImage in a class that is not a Component?

    I have an Image object loaded from a file using Toolkit, I want to draw it on a BufferedImage using g.drawImage( x, y, width, height, ImageObserver );
    later on I want to save the BufferedImage in a jpeg file using the converter.
    Since my class is not a subclass of Component (Panel, Applet, Canvas... ) what do I pass along as ImageObserver, nothing seems to be working, I can draw anything using g.draw... except an Image.
    Thanks...
    Fco. Espaillat

    Try extending ImageObserver. You only have to implement one method, and its hardly an implementation. I ussually have that method return true regardless of what is going on and it works.
    But to discourage bad programming style does anyone there know what that method is suppossed to return and how to find that out?

  • How to display tow images in a JPanel

    hello
    I want to display tow images at the same time in a class which extends a JPanel,and the super image is expected to move at will.But the super image is always overlaying the lower one.I have tried to call the setGlassPane() in a JFrame and it works!But how to do in a JPanel?
    Here is my code:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class SlideRheostat extends JPanel
    Image imageRheostat,imageSlip;
    Rectangle rec;
    public SlideRheostat()
         imageRheostat=Toolkit.getDefaultToolkit().getImage("imageRheostat.gif");
         imageSlip=Toolkit.getDefaultToolkit().getImage("imageSlip.gif");
    public void paint(Graphics g,Rectangle rec)
         g.drawImage(imageRheostat,0,0,imageRheostat.getWidth(),imageRheostat.getHeight(),this);
         g.drawImage(imageSlip,20,20,imageSlip.getWidth(),imageSlip.getHeight(),this);

    hello
    I want to display tow images at the same time in a class which extends a JPanel,and the super image is expected to move at will.But the super image is always overlaying the lower one.I have tried to call the setGlassPane() in a JFrame and it works!But how to do in a JPanel?
    Here is my code:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class SlideRheostat extends JPanel
    Image imageRheostat,imageSlip;
    public SlideRheostat()
    imageRheostat=Toolkit.getDefaultToolkit().getImage("imageRheostat.gif");
    imageSlip=Toolkit.getDefaultToolkit().getImage("imageSlip.gif");
    public void paint(Graphics g)
    g.drawImage(imageRheostat,0,0,imageRheostat.getWidth(),imageRheostat.getHeight(),this);
    g.drawImage(imageSlip,20,20,imageSlip.getWidth(),imageSlip.getHeight(),this);

  • How to draw an image onto a canvas3d?

    hi,
    i managed to draw onto a canvas 3d overwriting postRender() of canvas3d.
      public void postRender()
        J3DGraphics2D g = getGraphics2D();
        //  TEST BEGINN
          Image pic = this.getToolkit().createImage("Graphics" + File.separator + "start2.png");
          MediaTracker helpMT = new MediaTracker(this);
          helpMT.addImage(pic,0);
          try{
            helpMT.waitForAll();
          } catch(InterruptedException e) {}
          g.drawImage(pic,10,10,200,200,this);
          g.setColor(Color.yellow);
          g.drawString("yellow",20,300);
          g.setPaintMode();
          g.setColor(Color.red);
          g.drawString("red",20,320);
          g.setColor(Color.green);
          g.drawString("green",20,340);
          g.setColor(Color.orange);
          g.drawString("orange",20,360);
          g.flush(true);
        //  TEST ENDE
      }However the colors are totally messed up. red is purple, for example, and images are also shown with the wrong colors. What am I doin wrong, and how can I fix it?
    thanx,
    Usul

    Please, Im stuck.
    Here are the only two classes needed:
    Test2d.class:
    import java.awt.*;
    import com.sun.j3d.utils.universe.*;
    import javax.media.j3d.*;
    import javax.swing.*;
    public class Test2d extends JFrame
      public Test2d ()
        getContentPane().setLayout(new BorderLayout());
        Canvas3D c = new Visual_Canvas3D(SimpleUniverse.getPreferredConfiguration());
        getContentPane().add("Center", c);
        SimpleUniverse simpleU = new SimpleUniverse(c);
        BranchGroup scene = new BranchGroup();
        simpleU.getViewingPlatform().setNominalViewingTransform();
        scene.compile();
        simpleU.addBranchGraph(scene);
       public static void main(String[] args)
         Test2d mainApp = new Test2d();
         mainApp.setSize(800,600);
         mainApp.show();
    }Visual_Canvas3D.class:
    import java.awt.*;
    import javax.media.j3d.*;
    public class Visual_Canvas3D
    extends Canvas3D
      public Visual_Canvas3D(GraphicsConfiguration gc)
        super(gc);
      public void postRender()
          J3DGraphics2D g = getGraphics2D();
          g.setColor(Color.red);
          g.drawString("red",20,320);
          g.setColor(Color.green);
          g.drawString("green",20,340);
          g.setColor(Color.orange);
          g.drawString("orange",20,360);
          g.setColor(Color.yellow);
          g.drawString("yellow",20,100);
          g.flush(false);
    }Where could be the problem?

  • How to export my image with transparent bkground (CC)

    Before I ask my question, I want to point out I am currently exporting my image by going to File>Export>.PNG>(72PPI+Transparent)
    The issue im running into is; for example when I am exporting text, I am also exporting a certain amount of area around my image. How can I export the exact outline of my image? I have posted a screen shot of what im refering to.
    When I wanted to use my text image for a website I was building I noticed I couldnt get the image to center. I opened the image in paint and noticed I was exporting the area around my image aswell and not just the image itself. Hopefully the screen shots can explain my scenario a little better...
    I would like to export the text outline only. As you can see in paint I am exporting a fixed area around my image.
    ANY HELP IS GREATLY APPRECIATED!!!!!!!! THANK YOU -JON-

    The image was created in Illustrator. I opened the file in Photoshop and I see that area around my image aswell. I would like to just export the highlighted area. When im exporting through Illustrator, I would like to export a tighter area the image, not so much area around

  • How to add an image to the JPanel

    i have been searching for many to add in an iamge to the JPanel...but with error..can anyone kndly help?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class adv extends JPanel {
    ImageIcon pic = new ImageIcon("home.gif");
    public void paintComponent(Graphics g) {
    g.drawImage(pic,0,0,this);
    super.paintComponent(g);
    public static void main(String[] args) {
    adv mpg= new adv();
    mpg.setLayout(new GridLayout(5,1,15,15));
         JFrame window = new JFrame ("dv");
    window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);     
    window.add(mpg);
    window.setVisible(true);
    window.setSize (550,225);
    }

    i have try out the suggestion that u have provided...still with error...wat can i do to solve it? any other way?
    below is how i add to my program...
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class adv extends JPanel {
        ImageIcon pic = createImageIcon("home.gif");
        public void paintComponent(Graphics g) {
      super.paintComponent(g);
    g.drawImage(pic.getImage(),0,0,this);
        public static void main(String[] args) {
           /*adv mpg= new adv();
          mpg.setLayout(new GridLayout(5,1,15,15));
             JFrame window = new JFrame ("dv");
             window.setLayout(new BorderLayout());
             frame.add(mpg, BorderLayout.CENTER);
           window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);     
           window.add(mpg);
           window.setVisible(true);
           window.setSize (550,225);*/
           adv mpg = new adv();
           JFrame frame = new JFrame();
         frame.setLayout(new BorderLayout());
         frame.add(pic, BorderLayout.CENTER);
         frame.setSize(500, 500);
         frame.setVisible(true);
    }

  • How to drawing on image.

    Hi,
    I am developing one paint program. I am drawing over an image but the image is wash out when i am dragging mouse on canvas. But when i am clicking first on canvas before selecting any button. then selecting button after that it is working fine. Please help me
    Thanks in advance.
    Manveer

    The graphics context of your display object will erase when a repaint event is encountered--system generated or by code. If you do not have a persistent object displaying or the paint method does not containt the instruction to reproduce your image, then guess what? That's right you loose the image.
    You can paint to a BufferedImage and then do a drawImage in the overridden paint/paintComponent (AWT/SWING) of your display object. Without doing something like this, your image will dissapear mysteriously every time a system generated repaint happens.

  • How to superpose two image with transparency color

    Hi,
    I like to superpose two image with a transparency color. I know it is possible but i do not know on which API i can find it.
    thanks

    http://developer.java.sun.com/developer/JDCTechTips/2002/tt0618.html
    http://java.sun.com/products/jfc/tsc/articles/swing2d/
    Try these they discuss transparent images.
    rykk

Maybe you are looking for