Howto center an ImageIcon in a JPanel?

I'm loading some images using the ImageIcon api, but they appear at the top of the panel, how can I have them centered in the panel?
Here is the relevant code:
    label1 = new JLabel();
    label1.setIcon(image);
    panel.displayCard1Panel.add(label1);The displayCard1Panel is in the CENTER of a BorderLayout.
Thanks,
dsb5

>
Try this
// not tested
myPicci.setHorizontalAlignment(SwingConstants.CENTER);
myPicci.setVerticalAlignment(SwingConstants.CENTER);Doesn't seem to work. I've tried
    label1 = new JLabel(image, JLabel.LEFT);   
    label2 = new JLabel();
    label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label2.setIcon(image);
    panel.displayCard1Panel.add(label1);
    panel.displayCard2Panel.add(label2);to test but there is no change.

Similar Messages

  • How to remove an ImageIcon from a JPanel.

    I'm kind of new to java, and I'm trying to write a simple program that will change a picture in a window when a button is clicked. Is there a simple way to remove an ImageIcon from a JPanel. I tried the remove() method, but it says there is no constructor to handle remove(ImageIcon). This is the error I'm getting. I can/will post my code if you think it's necessary, but I didn't think it would be needed.
    PicChanger.java:64: cannot find symbol
    symbol : method remove(javax.swing.ImageIcon)
    location: class javax.swing.JFrame
    frame.remove(ii);
    ^

    Oh wow, that changes everything. Thanks for the information! Can't believe I missed that.

  • Howto center flash object in a page

    Hi,
    i am confused of how are whole pages(with all navigation, header,etc) generated. I tried to study html and css codes of generated pages but there is a lot of functions etc, so the first question: is there some tutorial where are described some processes of building pages(its division into iframes, divs, ...)?
    the second question: I need to make some page with full height and in that page i need to vertical center some object(ie flash), how should i do it?
    thnaks

    Hello Jiri
    This link for SAP help should be usefull for you.
    <a href="http://help.sap.com/saphelp_erp2005/helpdata/en/67/74de3fc6c6ec06e10000000a1550b0/frameset.htm">http://help.sap.com/saphelp_erp2005/helpdata/en/67/74de3fc6c6ec06e10000000a1550b0/frameset.htm</a>
    Regards
    Jamal

  • HOWTO: Draw on top of a JPanel without it beeing repainted?

    Hey,
    I have made a JPanel which draws some graphics with the use of the paintComponent() method. What I want now is a layer on top of this JPanel where I can draw a filled circle where the mousepointer is. How can this be achieved without the underlying JPanel beeing redrawn?
    - KHM

    Reminds me of The Glass Pane example
    http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html

  • ImageIcons... JPanels.... JLabels... help?

    Hello all.
    I am a noobie at this stuff (just to let y'all kno) and I'm having a hard time drawing/painting an ImageIcon on a JPanel. I'm not really sure, but I think it has something to do with the fact that the Graphics class is abstract (so obviously I can't make an instance of it) and therefore I can't pass a graphics object in a parameter without getting a NullPointerException or compiler error saying "g" has not been initialised.
    here's part of the code:
    ImageIcon image = new ImageIcon("C:\\marble.JPEG", "a marble");
              JLabel background = new JLabel(image);
              container.add(background, BorderLayout.CENTER);
    Any help would be greatly appreciated. :-)

    the method you need is
    setIcon()
    here's the earlier code, modified for the image to show after clicking the button
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setSize(600,400);//needs a size, otherwise frame will be very small (label is empty)
        setLocation(300,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        final JLabel lbl = new JLabel();
        p.add(lbl);
        getContentPane().add(p,BorderLayout.CENTER);
        JButton btn = new JButton("Show Image");
        getContentPane().add(btn,BorderLayout.SOUTH);
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            lbl.setIcon(new ImageIcon("C:\\Test.jpg","a marble"));
            pack();//will change the size of the frame, comment out and experiment
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How to use the Rectangle class to draw an image and center it in a JPanel

    I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
    I have divided the code into three parts. They are all supposed to be on one file in order to execute.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class CenterRect extends JPanel {
        public static Rectangle srcRect;
        Insets insets = null;
        Image image;
        MyImage imp;
        private double magnification;
        private int dstWidth, dstHeight;
        public CenterRect(MyImage imp){
            insets = getInsets();
            this.imp = imp;
            int width = imp.getWidth();
            int height = imp.getHeight();
            ImagePanel.init();
            srcRect = new Rectangle(0,0, width, height);
            srcRect.setLocation(0,0);
            setDrawingSize(width, height);
            magnification = 1.0;
        public void setDrawingSize(int width, int height) {
            dstWidth = width;
            dstHeight = height;
            setSize(dstWidth, dstHeight);
        public void paintComponent(Graphics g) {
            Image img = imp.getImage();
         try {
                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);
            catch(OutOfMemoryError e) {e.printStackTrace();}
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Opener().openImage();
    class Opener{
        private String dir;
        private String name;
        private static String defaultDirectory;
        JFrame parent;
        public Opener() {
            initComponents();
         public void initComponents(){
            parent = new JFrame();
            parent.setContentPane(ImagePanel.panel);
            parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
            parent.setVisible(true);
        public void openDialog(String title, String path){
            if (path==null || path.equals("")) {
                FileDialog fd = new FileDialog(parent, title);
                defaultDirectory = "dir.image";
                if (defaultDirectory!=null)
                    fd.setDirectory(defaultDirectory);
                fd.setVisible(true);
                name = fd.getFile();
                if (name!=null) {
                    dir = fd.getDirectory();
                    defaultDirectory = dir;
                fd.dispose();
                if (parent==null)
                    return;
            } else {
                int i = path.lastIndexOf('/');
                if (i==-1)
                    i = path.lastIndexOf('\\');
                if (i>0) {
                    dir = path.substring(0, i+1);
                    name = path.substring(i+1);
                } else {
                    dir = "";
                    name = path;
        public MyImage openImage(String directory, String name) {
            MyImage imp = openJpegOrGif(dir, name);
            return imp;
        public void openImage() {
            openDialog("Open...", "");
            String directory = dir;
            String name = this.name;
            if (name==null)
                return;
            MyImage imp = openImage(directory, name);
            if (imp!=null) imp.show();
        MyImage openJpegOrGif(String dir, String name) {
                MyImage imp = null;
                Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
                if (img!=null) {
                    imp = new MyImage(name, img);
                    FileInfo fi = new FileInfo();
                    fi.fileFormat = fi.GIF_OR_JPG;
                    fi.fileName = name;
                    fi.directory = dir;
                    imp.setFileInfo(fi);
                return imp;
    }

    This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
    class MyImage implements ImageObserver{
        private int imageUpdateY, imageUpdateW,width,height;
        private boolean imageLoaded;
        private static int currentID = -1;
        private int ID;
        private static Component comp;
        protected ImageProcessor ip;
        private String title;
        protected Image img;
        private static int xbase = -1;
        private static int ybase,xloc,yloc;
        private static int count = 0;
        private static final int XINC = 8;
        private static final int YINC = 12;
        private int originalScale = 1;
        private FileInfo fileInfo;
        ImagePanel win;
        /** Constructs an ImagePlus from an AWT Image. The first argument
         * will be used as the title of the window that displays the image. */
        public MyImage(String title, Image img) {
            this.title = title;
             ID = --currentID;
            if (img!=null)
                setImage(img);
        public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
             imageUpdateY = y;
             imageUpdateW = w;
             imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
         return !imageLoaded;
        public int getWidth() {
             return width;
        public int getHeight() {
             return height;
        /** Replaces the ImageProcessor, if any, with the one specified.
         * Set 'title' to null to leave the image title unchanged. */
        public void setProcessor(String title, ImageProcessor ip) {
            if (title!=null) this.title = title;
            this.ip = ip;
            img = ip.createImage();
            boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
         width = ip.getWidth();
         height = ip.getHeight();
         if (win!=null && newSize) {
                win = new ImagePanel(this);
        public void draw(){
            CenterRect ic = null;
            win = new ImagePanel(this);
            if (win!=null){
                win.addIC(this);
                win.getCanvas().repaint();
                ic = win .getCanvas();
                win.panel.add(ic);
                int width = win.imp.getWidth();
                int height = win.imp.getHeight();
                Point ijLoc = new Point(10,32);
                if (xbase==-1) {
                    xbase = 5;
                    ybase = ijLoc.y;
                    xloc = xbase;
                    yloc = ybase;
                if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
                    yloc = ybase+20;
                    int x = xloc;
                    int y = yloc;
                    xloc += XINC;
                    yloc += YINC;
                    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                    count++;
                    if (count%6==0) {
                        xloc = xbase;
                        yloc = ybase;
                    int scale = 1;
                    while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
                        if (scale>1) {
                   originalScale = scale;
                   ic.setDrawingSize(width/scale, height/scale);
        /** Returns the current AWT image. */
        public Image getImage() {
            if (img==null && ip!=null)
                img = ip.createImage();
            return img;
        /** Replaces the AWT image, if any, with the one specified. */
        public void setImage(Image img) {
            waitForImage(img);
            this.img = img;
            JPanel panel = ImagePanel.panel;
            width = img.getWidth(panel);
            height = img.getHeight(panel);
            ip = null;
        /** Opens a window to display this image and clears the status bar. */
        public void show() {
            show("");
        /** Opens a window to display this image and displays
         * 'statusMessage' in the status bar. */
        public void show(String statusMessage) {
            if (img==null && ip!=null){
                img = ip.createImage();
            if ((img!=null) && (width>=0) && (height>=0)) {
                win = new ImagePanel(this);
                draw();
        private void waitForImage(Image img) {
        if (comp==null) {
            comp = ImagePanel.panel;
            if (comp==null)
                comp = new JPanel();
        imageLoaded = false;
        if (!comp.prepareImage(img, this)) {
            double progress;
            while (!imageLoaded) {
                if (imageUpdateW>1) {
                    progress = (double)imageUpdateY/imageUpdateW;
                    if (!(progress<1.0)) {
                        progress = 1.0 - (progress-1.0);
                        if (progress<0.0) progress = 0.9;
    public void setFileInfo(FileInfo fi) {
        fi.pixels = null;
        fileInfo = fi;
    }

  • How do I move an imageicon from one side of a jpanel to opposite side

    Hi,
    I have a probelm on drag and drop imageicons on the same JPanel. At the moment I can place imageicons on the JPanel.
    How can detect mouse events on a specific imageicon on the jpanel?

    Hook your iPad up to your computer and iTunes and move them from within iTunes.
    Or
    Hold down on one of  your apps until they all start to wiggle. Then hold down on the ones you want to move and drag them on the screen. Drag them to the middle left to move them left,(such as from page 2 to page one) middle right ot move them right,(from page 2 to page 3) rearrange as you want.
    When you're done, tap the home key and everything should stop wiggling.

  • Help centering items on jpanel

    hi,
    i'm trying to center content on a jpanel, it doesn't seem to be working at all.
    RegisteredMark = new JLabel(new ImageIcon("registered.gif"));
    JPanel imageBottomPanel = new JPanel();
    imageBottomPanel.setLayout(new GridLayout(1,3));
    imageBottomPanel.add(RegisteredMark);
    counterLabel = new JLabel();
    String strCounter = String.valueOf(countOfNotesUsed);
    counterLabel.setText(strCounter);
    imageBottomPanel.add(counterLabel);
    //     imageBottomPanel.setAlignmentX(JPanel.CENTER_ALIGNMENT);When the above is put into my jpanel it does not center, it's left aligned, i've also tried using the last line, the commented one, but that did not do anything. the imageBottomPanel is later placed into another jpanel, which has a border layout, in the SOUTH position.
    Thanks.

    If I were going to try aligning anything there, I would try aligning RegisteredMark, since that's what you want to align. Not the JPanel. And did you know there is a Swing forum to post non-advanced questions like this?

  • Question on jpanel

    im making my own panel in which im going to extend JPanel, and have it be able to display different images when a button has been clicked on. my question is, is it possible to display gifs on a panel and call repaint() to have it appear? or what images am i allowed to display on a JPanel? Thanks in advance

    Here is a better, at least IMHO, solution:
    Add a JLabel to your JPanel. When you want to display an image on the panel simply call myLabel.setIcon(image). Here's a demo.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class LabelImageTest extends JFrame{
        JLabel imageLabel;
        ImageIcon imageIcon;
        Image imageOne;
        Image imageTwo;
        Image imageThree;
        public LabelImageTest() {
            initImages();
            buildGui();
        private void initImages() {
            imageOne = Toolkit.getDefaultToolkit().getImage("images/About24.gif");
            imageTwo = Toolkit.getDefaultToolkit().getImage("images/Add24.gif");
            imageThree = Toolkit.getDefaultToolkit().getImage("images/Bean24.gif");
        private void buildGui() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            mainPanel.add(buildCenterPanel(), BorderLayout.CENTER);
            mainPanel.add(buildButtonPanel(),BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        private void setImage(Image image){
           imageLabel.setIcon(new ImageIcon(image));
        private JPanel buildButtonPanel() {
            JPanel retPanel = new JPanel();
            JPanel innerPanel = new JPanel(new GridLayout(0,3,5,5));
            JButton buttonOne = new JButton("Image one");
            buttonOne.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                   setImage(imageOne);
            JButton buttonTwo = new JButton("Image two");
            buttonTwo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setImage(imageTwo);
            JButton buttonThree = new JButton("Image Three");
            buttonThree.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setImage(imageThree);
            innerPanel.add(buttonOne);
            innerPanel.add(buttonTwo);
            innerPanel.add(buttonThree);
            retPanel.add(innerPanel);
            return retPanel;
        private JPanel buildCenterPanel() {
            JPanel retPanel = new JPanel();
            retPanel.setPreferredSize(new Dimension(50,50));
            imageLabel = new JLabel();
            imageIcon = new ImageIcon();
            imageLabel.setIcon(imageIcon);
            retPanel.add(imageLabel);
            return retPanel;
        public static void main(String[] args) {
            new LabelImageTest();
    }Of course, you'll have to supply path to your own images. The nice thing about this is that you can pass in images from files or a self created image you've drawn.
    Cheers
    DB

  • Set Location of JPanel in another JPanel

    Hello, i want to set the location of a JPanel in another JPanel.
    This is my code:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package nemo;
    * @author Administrator
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class BackgroundImage extends JFrame
         JScrollPane scrollPane;
         ImageIcon icon;
            ImageIcon iconDrinken;
         Image image;
         public BackgroundImage() {
              icon = new ImageIcon("startpage.JPG");
                    iconDrinken = new ImageIcon("drankje.JPG");
              JPanel panel = new JPanel() {
                   protected void paintComponent(Graphics g) {
                        //  Dispaly image at at full size
                        g.drawImage(icon.getImage(), 0, 0, null);
                        super.paintComponent(g);
                    JPanel panelDrinks = new JPanel() {
                        protected void paintComponent(Graphics g) {
                            g.drawImage(iconDrinken.getImage(), 0, 0, null);
                            super.paintComponent(g);
                    panelDrinks.setOpaque( false );
              panelDrinks.setPreferredSize( new Dimension(200, 215) );
              panel.setOpaque( false );
              panel.setPreferredSize( new Dimension(400, 400) );
              scrollPane = new JScrollPane( panel );
              getContentPane().add( scrollPane );
                    panel.add(panelDrinks);
         public static void main(String [] args)
              BackgroundImage frame = new BackgroundImage();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(800, 600);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }When i execute this i get this:
    [http://img208.imageshack.us/img208/738/nowml5.jpg]
    And i want the image in the first white box from the left.
    But how to do it???
    I've tried .setLocation and .setBounds
    Edited by: Sven.nl on Apr 17, 2008 2:42 AM
    Edited by: Sven.nl on Apr 17, 2008 2:43 AM

    I already found it. Thanks anyway.
                    JPanel panelDrinks = new JPanel() {
                        protected void paintComponent(Graphics g) {
                            g.drawImage(iconDrinken.getImage(), 100, 200, 200, 215, null);
                            super.paintComponent(g);
                    panelDrinks.setOpaque( false );
              panelDrinks.setPreferredSize( new Dimension(800, 600) );
                    panelDrinks.setLocation(300, 300);
                      Edited by: Sven.nl on Apr 17, 2008 3:05 AM

  • Problem doing something based on JPanel size

    I have a JPanel (mainPane) with a BorderLayout which stretches to fit the space available to it.
    In the North I have a title.
    In the Center I am putting another JPanel (centerPane) (which may be bigger or smaller than the space available).
    I want to conditionally put a button in the South depending on whether all of the Center JPanel is displayed or not.
    Having trouble determining the size of the two panels at the time of laying out.
    Problem, until it has first been drawn, mainPanel.getSize().height always returns 0.
    Any ideas?

    I will need to do that too, in case the user resizes
    the whole frame later. However, my problem is when
    initially laying out the screen.
    I know the drawing is delayed until the event thread
    is free. Is there any way to force this to happen
    earlier.not the drawing bit, afaik. you could try doing a getLayout() to calculate the sizes etc. but i'm not sure..
    So I can make it layout the screen after I put the
    mainPanel on but before I add the centerPanel to the
    mainPanel.why can't you do the whole thing in the component adapter, that will be called not just when the user does a resize. as far as i understand your problem, you want to know when to show the button, and that would be the ideal place.
    but, hey, it's none of my business why you would want to do what you want to do ;)
    thomas

  • ImageIcon does not fill the whole button

    Hi all,
    i have a button, and i want an image to fill the whole button (without any space between borders and image).
    How i should do it?
    private JButton botonEnviar = new JButton(new ImageIcon("send.gif"));
    JPanel botonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
    botonPanel.add(botonEnviar);Thanks

    Try the following.
    botonEnviar.setMargins(new Insets(0, 0, 0, 0));
    botonEnviar.setBorder(...);

  • JPanel setOpaque(false) isn't transparent ?

    Hi,
    I've set a JPanel as the only thing added to a JFrame container. I've set a picture to this JPanel by using the following code
              JPanel temp = new JPanel()
                   public void paintComponent(Graphics g)
                         Dimension d = getSize();
                         g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
                        setOpaque( false );
                        super.paintComponent(g);
              };Now I've added another JPanel onto this one. I've set its background to RED, so there is a red square over my picture on my JFrame. However I want this JPanel to be fully transparent, so you can't actually see it at all, so the picture behind it on the original JPanel shows through.
    But when I use setOpaque(false), I just get a gray square instead of a red one, it doesn't show anything through at all.
    Anyone know why this would be ?
    Thanks

    Here you go, the background picture is not shining through. You'll have to change the jpg name to whatever you want to use.
    Thanks
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.border.*;
    public class OneToOneChat extends JFrame
         protected JPanel leftZone, rightZone, totalZone;
         protected JTextPane bottomLeftZone, topLeftZone;
         protected JScrollPane topScroll, bottomScroll;
         public static void main(String args[])
              new OneToOneChat();          
         public OneToOneChat()
              setSize(400,400);          
              setTitle("My Opaque Problem");
              setLocation(200,200);
              setResizable(false);     
              Container con = getContentPane();
              leftZone = new JPanel(new BorderLayout());
              rightZone = new JPanel(new BorderLayout());          
              totalZone = new JPanel(new BorderLayout());               
              topLeftZone = new JTextPane();                              
              bottomLeftZone = new JTextPane();     
              topScroll = new JScrollPane(topLeftZone, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);          
                    topScroll.setPreferredSize(new Dimension(250,150));          
              bottomScroll = new JScrollPane(bottomLeftZone,
                                           JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                           JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);                                      
              bottomScroll.setPreferredSize(new Dimension(250,150));                                      
              rightZone.setOpaque(false);          
              rightZone.setBackground(Color.RED);          
              rightZone.setBorder( new LineBorder(Color.GREEN) );          
              rightZone.setPreferredSize(new Dimension(250,300));                                             
              leftZone.add(topScroll, "North");
              leftZone.add(bottomScroll,"South");
              totalZone.add(leftZone,"West");
              totalZone.add(rightZone,"East");
              final ImageIcon icon = new ImageIcon("ripple.jpg");                    
              JPanel temp = new JPanel()
                   public void paintComponent(Graphics g)
                        Dimension d = getSize();
                        g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
                        setOpaque( false );
                        super.paintComponent(g);
              temp.setBorder(new EmptyBorder(8,8,8,8));                    
              temp.add(totalZone);                                             
              con.add(temp);     
              pack();
              setVisible(true);
    }

  • How to make an imageicon to be resized to fit the button

    Hi all,
    I am working on this problem, which has a JButton, Image and Text all one above another . The graphic here is a rectangular box.
    The application works fine for an 800 X 600 resolution, but when the resolution is changed to 1024 X 728, only the Jbutton and the text are getting bigger(logic already present), but not the graphical icon which sits on top of the button.
    So I tried to scale the image and then redraw it using the drawImage() of the graphics object. But it wouldnt show up, so i set the Opaque property to false for the Jbutton, to make the image visible. Then the image showed up as wanted, but when a mouse click event occurs on that button,the button is not getting highlighted and some weird behaivour happens.
    If anyone can throw some light on this, i would greatly appreciate it.
    Thanks in advance

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ImageOnButton extends JFrame { 
    public ImageOnButton() {   
      ImageIcon icon = new ImageIcon("SndImage.jpg");
        JPanel content = (JPanel)getContentPane();
        content.setLayout(new FlowLayout());
        JButton myButton = new MyButton("I am Button",icon.getImage());
        content.add(myButton);
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
    public static void main(String[] args) {
        ImageOnButton test = new ImageOnButton();
        test.setSize(200,200);
        test.show();
      class MyButton extends JButton {
        Image image;
        public MyButton(String Text, Image Image) {
          super(Text);
          setOpaque(false);
          image=Image;
        public void paint(Graphics g) {
          g.drawImage(image, 0,0, getWidth(), getHeight(), this);
          super.paint(g);
    }

  • Copying image to jpanel

    when i copy an image to jpanel using jlabel i.e
    jlabel lab = new jlabel(new Iconimage("xyz.jpg"));
    i cannot listen to any keys being pressed on the label when i want to copy the image onto a clip board( cntrl C). Is there any method of listening to keys being pressed on jlabel or a method to display the image on jpanel which listens to keys.

    can give code to draw image on Panel.
    icon = new ImageIcon("backUp.gif");
    JPanel panel = new JPanel()
         protected void paintComponent(Graphics g)
              g.drawImage(icon.getImage(), 0, 0, null);
              super.paintComponent(g);
    panel.setOpaque( false );

Maybe you are looking for

  • Itunes wont open after certain point

    okay so i upgraded my itunes and every single time i try to open it, this screen comes up that says itunes setup assistant at the top, and it starts to tell me about how i can download album artwork from the internet and all this, so when i go to cli

  • 4G LTE iPhone 5: Carrier Settings Update never came

    Hello, Just to say, before I start: This question is related to Switzerland's Swisscom's 4G LTE network and iPhone 5. I have updated to iOS 6.1 (for Swisscom 4G LTE compatibility, it's now compatible), but didn't get the carrier settings update, and

  • Invoice Verification (MIRO) posting, showing an error on Tax Code

    Hello When i am making MIRO posting it is showing that the specific tax code which i has given is not maintained in the Tax Procedure, but i have checked all the CIN Configurations, Activated the CIN and Tax Procedure is assigned to Country also and

  • Newbie Help Needed: Data Binding

    Okay, lemme see if I can possibly explain this issue clearly enough... (The whole explanation of the object graph may very well be superfluous, so you can probably skip to the bottom.) I have a whole object graph that I've downloaded from my server t

  • Is there any working flash player?

    Hello all, Excuse me, but I'm getting really irrtated now. My (multiple) problems with adobe flash player started in june 2012 after I made the stupid decision to update it. If I get any version to work properly again I certainly will not touch it fo