Image in the JPanel

Hello guys,
I am using netBeans 4.0.
I want to put a JPG image as the background in a JPanel.In netBeans IDE I cant do it. Is there a way to do this?
Thanks

Probably not. Learn how to code this is Java yourself. Search the forum using keywords "background image" and I believe you should file some solutions from other postings.

Similar Messages

  • 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 do you change the image in a JPanel?

    Hey! (firstly, i need to use image on a JPanel, label&icon not an option).
    I've made my JPanel class
        public class DrawingPanel extends JPanel {
            Image img;
            DrawingPanel() {
                Image img = Toolkit.getDefaultToolkit().getImage("13.jpg"); //default image at startup
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                // Use the image width & height to find the starting point
                int imgX = getSize ().width/2 - img.getWidth (this);
                int imgY = getSize ().height/2 - img.getHeight (this);
                //Draw image centered in the middle of the panel   
                g.drawImage (img, 0, 0, this);
            } // paintComponent
        } // DrawingPanelAnd I've made my instance of it and added it to the Frame:
        DrawingPanel imagePanel = new DrawingPanel();Now, I need to change the image on the JPanel according to the user's input. I have the string of the location of the new image. How do I update the JPanel to display this new image? Any help greatly appreciated!!

    Well... You could just add a method in your class which sets the image according to the new image name you provided. Something like this:
        public class DrawingPanel extends JPanel {
            Image img;
            DrawingPanel() {
                img = Toolkit.getDefaultToolkit().getImage("13.jpg"); //default image at startup
            public void setImage(String imageName) {
                    img = Toolkit.getDefaultToolkit().getImage(imageName); //Loading the desired image
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                // Use the image width & height to find the starting point
                int imgX = getSize ().width/2 - img.getWidth (this);
                int imgY = getSize ().height/2 - img.getHeight (this);
                //Draw image centered in the middle of the panel   
                g.drawImage (img, 0, 0, this);
            } // paintComponent
        } // DrawingPanel

  • Help! Read raw Image data from a file and display on the JPanel or JFrame.

    PLEASE HELP, I want to Read Binary(Raw Image)data (16 bit integer) from a file and display on the JPanel or JFrame.

    Hey,
    I need to do the same thing. Did you find a way to do that?
    Could you sent me the code?
    It's urgent, please.
    My e-mail is [email protected]

  • How to moving image or graphic on the JPanel??

    Hi,
    Everybody got any idea to do using mouse listener to click and moving the image or graphic and then to put the object at any coordinate on the JPanel???
    Thank to reply..

    You don't
    You cannot use other countries itunes stores.
    Sorry

  • How do you set an image into the background of a JPanel or JFrame?

    How do you set an image into the background of a JPanel or JFrame?

    Something like this, Ive thrown in an ImageIcon on a
    button too for good measure.
    import java.awt.*;
    import javax.swing.*;
    public class JFrameImage extends JFrame {
    public JFrameImage() {
    Container c    = getContentPane();
    JPanel panel = new JPanel(){
                 public void paintComponent(Graphics g)     {
    ImageIcon img = new
    = new ImageIcon("background.jpg");
                      g.drawImage(img.getImage(), 0, 0, null);
                      super.paintComponent(g);
            panel.setOpaque(false);
    ImageIcon icon = new ImageIcon("onButton.jpg");
    JButton button = new JButton(icon);
    panel.add(button);
    c.add(panel);
    public static void main(String[] args) {
    JFrameImage frame = new JFrameImage();
    frame.setSize(200,200);
    frame.setVisible(true);
    Going totally fancy pants
    ImageIcon bigImage = new ImageIcon(bgImage.getImage().getScaledInstance(getWidth(), getHeight(),Image.SCALE_REPLICATE));
    g.drawImage(bigImage.getImage(), 0, 0, this); Will scale the image to the size of the panel
    whereas
    for (int y = 0; y  < getHeight(); y = y + image.getHeight(null))
    for (int x = 0; x< getWidth(); x = x + image.getWidth(null))
    g.drawImage(image, x, y, this); Will give a tiled effect
    Try tiling with an animated gif and bring your processor to a standstill.

  • Animated GIF Image on a JPanel.

    How can I display an animated GIF image on a JPanel? It should animate after displaying.
    Regards

    I think this code should display an animated GIF image on a JPanel.
    -Mani
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.*;
    public class Animation {
    public static void main(String args[]) {
    JLabel imageLabel = new JLabel();
    JLabel headerLabel = new JLabel();
    JFrame frame = new JFrame("JFrame Animation");
    JPanel jPanel = new JPanel();
    //Add a window listner for close button
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add the header label
    headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
    headerLabel.setText("Animated Image!");
    jPanel.add(headerLabel, java.awt.BorderLayout.NORTH);
    //frame.getContentPane().add(headerLabel, java.awt.BorderLayout.NORTH);
    // add the image label
    ImageIcon ii = new ImageIcon("d:/dog.gif");
    imageLabel.setIcon(ii);
    jPanel.add(imageLabel, BorderLayout.CENTER);
    frame.getContentPane().add(jPanel, java.awt.BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

  • Problm with 'notepad' code..image of the buttons not displayed..help.. ;-(

    I have a source code for developing a notepad but the problem is that when i run it the buttons which i've used as shortcuts don't have there photos displayed on them... they just come across as a rectangular button rather than a cut or a copy photo...i've even saved those images in the c drive only where other files like .class file are stored still its not working...plz help...
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class Notepro extends JFrame implements ActionListener
         JMenuBar mbar;
         JMenu file,edit,format,font,font1,font2;
         JMenuItem item1,item2,item3,item4;
         JMenuItem item5,item6,item7,item8,item9,item10;
         JMenuItem fname1,fname2,fname3,fname4;
         JMenuItem fstyle1,fstyle2,fstyle3,fstyle4;
         JMenuItem fsize1,fsize2,fsize3,fsize4;
         JButton button,button1,button2,button3,button4,button5;
         JPanel mainpanel;
         JTextArea text;
         JScrollPane jsp;
         String command=" ";
         String str=" ";
         String str1=" ",str2=" ",str3=" ";
         String str4=" ";
         String str6=" ";
         String str7=" ",str8=" ",str9=" ";
         int len1;
         int i=0;
         int pos1;
         int len;
         public Notepro(String str)
         super(str);
         mainpanel=new JPanel();
         mainpanel=(JPanel)getContentPane();
         mainpanel.setLayout(new FlowLayout());
        MyWindowAdapter adapter=new MyWindowAdapter(this);     
        addWindowListener(adapter);
         mbar=new JMenuBar();
         setJMenuBar(mbar);
         file=new JMenu("File");
         edit=new JMenu("Edit");
         format=new JMenu("Format");
         file.add(item1=new JMenuItem("New..."));
         file.add(item2=new JMenuItem("Open"));
         file.add(item3=new JMenuItem("Save As..."));
         file.add(item4=new JMenuItem("Exit"));
         mbar.add(file);
         edit.add(item5=new JMenuItem("Cut"));
         edit.add(item6=new JMenuItem("Copy"));
         edit.add(item7=new JMenuItem("Paste"));
         edit.add(item8=new JMenuItem("Delete"));
         edit.add(item9=new JMenuItem("Select All"));
         mbar.add(edit);
    format.add(item10=new JMenuItem("Font"));
         mbar.add(format);
            button = new JButton(new ImageIcon("new.gif"));
              mainpanel.add(button);
              button1 = new JButton(new ImageIcon("open.gif"));
              mainpanel.add(button1);
              button2 = new JButton(new ImageIcon("save.gif"));
              mainpanel.add(button2);
              button3 = new JButton(new ImageIcon("copy.gif"));
              mainpanel.add(button3);
              button4 = new JButton(new ImageIcon("cut.gif"));
              mainpanel.add(button4);
              button5 = new JButton(new ImageIcon("paste.gif"));
              mainpanel.add(button5);
         item1.addActionListener(this);
         item2.addActionListener(this);
         item3.addActionListener(this);
         item4.addActionListener(this);
         item5.addActionListener(this);
         item6.addActionListener(this);
         item7.addActionListener(this);
         item8.addActionListener(this);
         item9.addActionListener(this);
         item10.addActionListener(this);
         button.addActionListener(this);
         button1.addActionListener(this);
         button2.addActionListener(this);
         button3.addActionListener(this);
         button4.addActionListener(this);
         button5.addActionListener(this);
         text=new JTextArea(60,80);
         mainpanel.add(text);
    jsp=new JScrollPane(text);
            mainpanel.add(jsp);
           public void actionPerformed(ActionEvent ae)
              if(ae.getSource()==button4)
              str=text.getSelectedText();
              i=text.getText().indexOf(str);
              text.replaceRange(" ",i,i+str.length());
              if(ae.getSource()==button)
              dispose();
              Notepro note1 = new Notepro("Untitled-Notepad");
              note1.setSize(500,500);
              note1.setVisible(true);
              command=(String)ae.getActionCommand();
              if(command.equals("New..."))
              dispose();
              Notepro note1 = new Notepro("Untitled-Notepad");
              note1.setSize(500,500);
              note1.setVisible(true);
              try
              if((command.equals("Open"))||(ae.getSource()==button1))
              str4=" ";
              FileDialog dialog=new FileDialog(this,"Open");
              dialog.setVisible(true);
              str1=dialog.getDirectory();
              str2=dialog.getFile();
              setTitle(str2);
              str3=str1+str2;
              File f=new File(str3);
              FileInputStream fobj=new FileInputStream(f);
              len=(int)f.length();
              for(int j=0;j<len;j++)
                   char str5=(char)fobj.read();
                   str4=str4 + str5;
                text.setText(str4);
              this.text.setText(str4);
              catch(IOException e)
              try
              if((command.equals("Save As..."))||(ae.getSource()==button2))
              FileDialog dialog1=new FileDialog(this,"Save As",FileDialog.SAVE);
              dialog1.setVisible(true);
              str7=dialog1.getDirectory();
              str8=dialog1.getFile();
              str9=str7+str8;
              str6=text.getText();
              len1=str6.length();
              byte buf[]=str6.getBytes();
              File f1=new File(str9);
              FileOutputStream fobj1=new FileOutputStream(f1);
              for(int k=0;k<len1;k++)
              fobj1.write(buf[k]);
              fobj1.close();
              this.setTitle(str8);
              catch(IOException e){}
              if(command.equals("Exit"))
              System.exit(0);
              if((command.equals("Cut"))||(ae.getSource()==button4))
              str=text.getSelectedText();
              i=text.getText().indexOf(str);
              text.replaceRange(" ",i,i+str.length());
              if((command.equals("Copy"))||(ae.getSource()==button3))
              str=text.getSelectedText();
              if((command.equals("Paste"))||(ae.getSource()==button5))
              pos1=text.getCaretPosition();
              text.insert(str,pos1);
              if(command.equals("Delete"))
              String msg=text.getSelectedText();
              i=text.getText().indexOf(msg);
              text.replaceRange(" ",i,i+msg.length());
              if(command.equals("Font"))
              MyFont  m=new MyFont(this);
         public static void main(String args[])
         Notepro note = new Notepro("Untitled-Notepad");
         note.setSize(500,500);
         note.setVisible(true);
    class MyWindowAdapter extends WindowAdapter
    Notepro mynote;
    MyWindowAdapter(Notepro mynote)
      this.mynote=mynote;
    public void windowClosing(WindowEvent we)
      System.exit(0);
    class MyFont extends Dialog implements ActionListener,ItemListener
    GraphicsEnvironment ge;
    java.awt.List l1,l2,l3;
    Button b1,b2;
    Font f1[];
    String f[];
    int i,j;
    Notepro p;
    TextField tf1,tf2,tf3;
    Label ll1,ll2,ll3;
    String fn;
    int fs,fsize;
    public MyFont(Notepro myno)
         super(myno,"Font",true);
      setLayout(null);
    p=myno;
      ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
      l1=new java.awt.List();
      l2=new java.awt.List();
      l3=new java.awt.List();
      b1=new Button("OK");
      b2=new Button("CANCEL");
    tf1=new TextField(10);
    tf2=new TextField(10);
    tf3=new TextField(10);
    ll1=new Label("Font");
    ll2=new Label("Font Style");
    ll3=new Label("Size");
         ll1.setBounds(20,60,100,20);
         add(ll1);
         tf1.setBounds(20,80,100,20);
         add(tf1);
            l1.setBounds(20,100,100,150);
            add(l1);
         ll2.setBounds(140,60,100,20);
         add(ll2);
         tf2.setBounds(140,80,100,20);
         add(tf2);
       l2.setBounds(140,100,100,150);
      add(l2);
         ll3.setBounds(260,60,100,20);
         add(ll3);
         tf3.setBounds(260,80,100,20);
         add(tf3);
           l3.setBounds(260,100,100,150);     
      add(l3);
         b1.setBounds(380,70,80,20);
      add(b1);
         b2.setBounds(380,95,80,20);
      add(b2);
      f=ge.getAvailableFontFamilyNames();
      for(i=0;i<f.length;i++)
       l1.add(f);
    l2.add("Regular");
    l2.add("Bold");
    l2.add("Italic");
    l2.add("BoldItalic");
    for(i=8;i<=72;i+=2)
         l3.add(String.valueOf(i));
    b2.addActionListener(this);
    b1.addActionListener(this);
    l1.addItemListener(this);
    l2.addItemListener(this);
    l3.addItemListener(this);
    setSize(480,280);
    setResizable(false);     
    setVisible(true);
    public void actionPerformed(ActionEvent fe)
    if(fe.getSource()==b2)
    dispose();
    if(fe.getSource()==b1)
         p.text.setFont(new Font(fn,fs,fsize));
         dispose();
    public void itemStateChanged(ItemEvent ie)
         if(ie.getSource()==l1)
    tf1.setText(l1.getSelectedItem());
         fn=tf1.getText();
         if(ie.getSource()==l2)
    tf2.setText(l2.getSelectedItem());
         if(tf2.getText().equals("Bold"))
              fs=Font.BOLD;
         else
    if(tf2.getText().equals("Italic"))
              fs=Font.ITALIC;
         else
              if(tf2.getText().equals("BoldItalic"))
              fs=Font.BOLD+Font.ITALIC;
         else
              fs=Font.PLAIN;     
         if(tf2.getText()=="")
         tf2.setText("Regular");
         fs=Font.PLAIN;
         if(ie.getSource()==l3)
         tf3.setText(l3.getSelectedItem());
         fsize=Integer.parseInt(tf3.getText());
    if(tf3.getText()=="")
                   fsize=8;

    swatschiks wrote:
    i checked it again but the files were in c drive only...nwaz is my link "open.gif" ok? maybe the problem lies in the links? Can u suggest me smthng? M a newbee..so plz if u can b more specific...i wud b gr8ful...need d help urgentlyOne word of unasked for advice: Please avoid unnecessary abbreviations in your posts here. I recommend this for several reasons:
    1) Programming is an exercise in precision. When you communicate here (or anywhere) about programming issues and questions, you want this communication to be as clear as possible to avoid any chance for ambiguity. I'd say at least half the answers here are requests for clarification. Let's avoid that.
    2) For many here, English is not their first (or second or third) language. It's hard enough for them to understand what people are posting here much less if it's couched in obscure and non-standard abbreviations.
    3) Extra letters don't cost anything here, so you might as well use them.
    4) It makes the poster seem a bit immature and thus for some not worthy of help.
    That being said, what are the full paths of: your image files, your class files, and what package is your program in?
    In that same package, what happens if you compile and run this program?
    import java.io.File;
    public class WhereAreMyFiles
      public static void main(String[] args)
        File myFile = new File("Fubar.txt");
        System.out.println(myFile.getAbsolutePath());
    }Notice the output very closely because that's where Java is looking to find your image files.

  • How to use a backgroud image in a JPanel.....

    hi,
    How can I display a background image for a JPanel.....
    I have searched this forum but all solutions I found are where JPanel at the end has to be displayed on a frame in an application...
    I need to use JPanel on Applet.......
    Actually I am switching JPanels on JApplet as screens for a game....
    I need to display background image for one of the JPanel class that has to be called by an Applet class....
    Thanks a lot for any help.

    Thanks a lot for your help.
    How do we specify URL to use an image from net. Is itt like I open an image file on some website & use its address? Kindly add here some website too so that its more clear for me.
    Thanks a lot for any help & all help your provided previously.
    String imageFilePath = "urlOfMyImageFile"; // I am asking about parameter to be used here
    ImageIcon ii = new ImageIcon(imageFilePath);
    Image image = ii.getImage();

  • 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 paint image in the JInternalFrame Urgent plz

    sir i want to draw a image on the back side of the JInternalFrame
    how can i do
    I do this job by using the following code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class MyInternalFrame extends JInternalFrame
    MyButtonPanel2 panel=new MyButtonPanel2();
    public static JPanel p=new JPanel();
    ImageIcon img=new ImageIcon("images/beach.jpg");
    JLabel backlabel;
    public static int w=376,h=50;
    MyInternalFrame(int width,int height,String str)
    setOpaque(false);
    this.setIconifiable(true);
    this.setSize(width,height);
    this.setTitle(str);
    this.setFrameIcon(new ImageIcon("images/smileyr.gif"));
    setMinimumSize(new Dimension(width,height));
    setPreferredSize(new Dimension(width,height));
    this.getContentPane().setLayout(null);
    panel.setBounds((width/2)-188,height-84,w,h);
    p.setLayout(null);
    int imgwidth=img.getIconWidth();
    int imgheight=img.getIconHeight();
    if((imgwidth<this.getWidth()) || (imgwidth>this.getWidth()))
    imgwidth=this.getWidth();
    if((imgheight<this.getHeight()) || (imgheight>this.getHeight()))
    imgheight=this.getHeight();
    backlabel=new JLabel(img);
    backlabel.setBounds(0,0,imgwidth,imgheight);
    p.add(backlabel,new Integer(Integer.MIN_VALUE));
    p.setBounds(0,0,width,height);
    this.getContentPane().add(panel,new Integer(Integer.MAX_VALUE));
    this.getContentPane().add(p);
    setVisible(true);
    but when i add another panel in the object p the component of another
    panel does not apper like this
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class companypanel extends MyInternalFrame
    LimitTextF nametxt=new LimitTextF(30,50,24);
    MyLabel name=new MyLabel("Company Name");
    LimitTextF codetxt=new LimitTextF(4,50,24);
    MyLabel code=new MyLabel("Company Code");
    companypanel(int width,int height,String str)
    super(width,height,str);
    name.setBounds(10,20,100,25);
    nametxt.setBounds(140,20,80,25);
    super.p.add(name);super.p.add(nametxt);
    plz tell me how can i do?

    These links will help.
    http://java.sun.com/products/jfc/tsc/articles/swing2d/
    http://java.sun.com/j2se/1.4.2/docs/guide/2d/spec/j2d-awt.html
    http://forum.java.sun.com/thread.jsp?forum=31&thread=409047
    rykk

  • 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);
    }

  • Resizing JFrame on button click to show an image on the JFrame

    Dear All,
    I have a JFrame which has an empty label. On button click I want to set an icon for the label and want the JFrame to be resized to show that icon. I am using frame.pack() and I am not using any other sizing function. The code that I have right now, prints the image on the panel, but does not resize the frame to show the image. Pleae could someone help.package gui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class ComponentDemo extends JPanel implements ActionListener,
    ItemListener, MouseListener, KeyListener {
         private JTextArea textarea;
         private JButton button;
         private final static String newline = "\n";
         private JLabel imageIcon;
         public ComponentDemo() {
              button = new JButton("JButton welcomes you  to CO2001");
              button.addActionListener(this);
              add(button);
              textarea = new JTextArea(10, 50);
              textarea.setEditable(false);
              addMouseListener(this);
              textarea.addKeyListener(this);
              JScrollPane scrollPane = new JScrollPane(textarea);
              add(scrollPane);
              imageIcon = new JLabel();
              add(imageIcon);
              setBackground(Color.pink);
              new JScrollPane(this);
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("Simple FrameDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation(700, 200);
              // get the content pane and set the background colour;
              frame.add(new ComponentDemo());
         //     frame.setSize(screenSize);
              // frame.getContentPane().setBackground(Color.cyan);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setResizable(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         @Override
         public void actionPerformed(ActionEvent e) {
              // TODO Auto-generated method stub
              if (e.getSource() instanceof JButton) {
                   // System.out.println(e.getSource());
                   String text = ((JButton) e.getSource()).getText();
                   textarea.append(text + newline);
                   textarea.setBackground(Color.cyan);
                   textarea.setForeground(Color.BLUE);
                   textarea.setCaretPosition(textarea.getDocument().getLength());
                   imageIcon.setIcon(createImageIcon("SwingingDuke.png",
                   "Image to be displayed"));
         @Override
         public void itemStateChanged(ItemEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseClicked(MouseEvent arg0) {
              textarea.append("A Mouse click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.green);
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent e) {
              System.out.println(e.getKeyChar());
              textarea.append("The key " + e.getKeyChar()
                        + " click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.YELLOW);
              textarea.setFont(new Font("Arial", Font.ITALIC, 16));
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyReleased(KeyEvent e) {
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.green);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyTyped(KeyEvent e) {
              // TODO Auto-generated method stub
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.blue);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected ImageIcon createImageIcon(String path, String description) {
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null) {
                   System.out.println("found");
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
    }

    myJPanel.setPerferredSize(new Dimension(new_width, new_hight));
    myJFrame.pack();

  • Copy and paste a image to the clipboard

    Hi,
    Is there anybody who knows how to copy and paste an image to the clipboard in jdk 1.3.0.
    I want make a image copy of my app like this (Panel):
    Image image = (Image)this.createImage(this.getWidth(), this.getHeight());
    Graphics g = image.getGraphics();
    this.paint(g);
    BufferedImage bufImage = (BufferedImage)image;
    Now i will send this bufImage or the image to the clipboard.
    How will it works?
    Thanks a lot.

    Hi,
    I m having similar type of problem but with JPanel not with image. i m able to copy paste a JPanel using same clipboard but i want some more operations like after zoomin my JPanel , i want that now if i copy the image of Jpanel it should be the copy of original size of JPanel not the zoomed one but in my application it is showing the blank picture
    for zoom fit size of JPanel its working ok.
    please advice me what should i do

Maybe you are looking for

  • Error: no boot disk has been detected or the disk has failed. I have a hp pavilion 23

    I got this computer December 2013. It has hardly been used and has displayed this in the past. Now it displays this and won't do anything. It makes a clicking type sound. I got it for Christmas and don't think there was a disk that came with it. I ha

  • Resizing questions

    I have my own large format printer which accepts 54" wide rolls of media. I plan on printing a number of photos on canvas, and am wondering about a few things: - If I wish to make a 40" x 30" print, what is the correct way to re-size the image in Pho

  • How do I open / run Cognos Impromptu Report from CSharp

    Hi, I am new to Csharp and using C# for my application development and I need to load Cognos Impromptu application and run a report from my application automatically and run the report to create ascii text file. Is there any code is available? I have

  • Change purchase requisition item number

    Hi, I want to copy an existing line item in the PR but, also I want to assign it the item number. Right now this field is display only for existing line items. Example: I have one line item with item number 10. Item number can not be changed (display

  • Record SAP sessions

    Hi, Is there a way to record SAP sessions other than SAP scripting? With SAP scripting there is a server-enablement needed, is this  a one time activity? Is it the same for client-enablement too?   I read an article about SAP Automation suite. But th