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

Similar Messages

  • 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 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 add an image file to Oracle db?

    Need help urgently....Anybody knows how to add an image file (example: jpg)into one of the fields in Oracle database??

    This will do the job..
    package forum;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    //import oracle.sql.*;
    Wanneer een request.getInputStream wordt geconferteerd naar een "String" (zie later) dan ziet de output in tekstformaat er als volgt uit:
    -----------------------------7d280152604f4 Content-Disposition: form-data; name="oploadfile"; filename="C:\WINNT\Profiles\mvo\Desktop\boodschap.txt" Content-Type: text/plain Deze boodschap dient te worden ge-insert in de database. -----------------------------7d280152604f4 Content-Disposition: form-data; name="StadID" 1234 -----------------------------7d280152604f4 Content-Disposition: form-data; name="SuccessPage" /forum/error.jsp -----------------------------7d280152604f4--
    of opgesplitst
    contentType........... multipart/form-data; boundary=---------------------------7d235ade00f0
    filename.............. "C:\Documents and Settings\Administrator\Desktop\boodschap.txt"
    MIME type............. text/plain
    Wat in database moet.. Dit is de eigenlijke boodschap die moet worden ge-insert in de database.
    Eind boundary......... -----------------------------7d235ade00f0 Content-Disposition: form-data; name="file1"; filename="" Content-Type: application/octet-stream -----------------------------7d235ade00f0--
    We gaan achtereenvolgens:
    1. Kijken of het van het "multipart/form-data" type is (uploaden) en strippen van eerste boundery.
    1.a Geen "multipart/form-data" ? dan... error message
    1.b Groter dan MAX_SIZE ?..dan .. error message
    2. Filenaam van de te uploaden file uitlezen
    3. Mimetype bepalen en bepalen in welke positie van de string het Mimetype ophoudt, cq waar te uploaden file begint
    4. Bepalen waar eind boundery begint
    5. De eigenlijke file uitlezen
    6. Terug converteren naar bytes
    public class WriteBlob extends HttpServlet {
    public static final int MAX_SIZE = ParameterSettings.imageUpload;
    String successMessage = "";
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    * Process the HTTP Get request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataInputStream in = null;
    FileOutputStream fileOut= null;
    PrintWriter out = response.getWriter();
    int kb_size = 0;
    boolean pass2 = true;
    String message = "";
    String responseRedirect = "/forum/uploaden.jsp?message="+" Uploaden geslaagd";
    try
    //get content type of client request
    String contentType = request.getContentType();
    // Start stap 1...content type is multipart/form-data
    if(contentType != null && contentType.indexOf("multipart/form-data") != -1)
    //open input stream
    in = new DataInputStream(request.getInputStream());
    //get length of content data
    int formDataLength = request.getContentLength(); // totale lengte van de inputstream
    //initieer een byte array om content data op te slaan
    byte dataBytes[] = new byte[formDataLength];
    //read file into byte array
    int bytesRead = 0;
    int totalBytesRead = 0;
    int sizeCheck = 0;
    while (totalBytesRead < formDataLength)
    //kijken of de file niet te groot is
    sizeCheck = totalBytesRead + in.available();
    if (sizeCheck > MAX_SIZE)
    pass2 = false;
    message = "Sorry. U kunt slechts bestanden uploaden tot een grootte van 500KB";
    responseRedirect = "/forum/uploaden.jsp?message="+message;
    bytesRead = in.read(dataBytes, totalBytesRead,formDataLength);
    totalBytesRead += bytesRead;
    if (pass2==true)
    kb_size = (int)(formDataLength/1024);
    //create string from byte array for easy manipulation
    String file = new String(dataBytes);
    /*get boundary value (boundary is a unique string that separates content data)
    contentType........... multipart/form-data; boundary=---------------------------7d235ade00f0
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex+1, contentType.length());
    // Stap 2.....bepaal de naam van de upload file
    // filename.............. "C:\Documents and Settings\Administrator\Desktop\boodschap.txt"
    String saveFile = file.substring(file.indexOf("filename=\"")+10);
    saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\"")); //naam van de file...boodschap.txt
    String saveFileName = saveFile;
    // Stap 3..Bepaal MIME Type en de positie van eind mime type in string
    voorbeeld: -----------------------------7d23d21220524 Content-Disposition: form-data; name="file0"; filename="C:\WINNT\Profiles\mvo\Desktop\z clob.txt" Content-Type: text/plain
    String restant = "";
    int pos; //position in upload file
    // bijv .. filename="C:\Documents and Settings\Administrator\Desktop\boodschap.txt"
    pos = file.indexOf("filename=\"");
    //find position of content-disposition line
    pos = file.indexOf("\n",pos)+1; // eing file naam + spatie
    // onderstaand geeft bijv Content-Type: text/plain
    restant = file.substring(pos,file.indexOf("\n",pos)-1);
    restant = restant.substring(restant.indexOf(":")+2,restant.length()); // MIME type
    String mimeType = restant;
    //find position of eind content-type line
    pos = file.indexOf("\n",pos)+1;
    //find position of blank line
    pos = file.indexOf("\n",pos)+1;
    int start = pos;
    // Stap 4 eind boundary
    /*find the location of the next boundary marker (marking the end of the upload file data)*/
    int boundaryLocation = file.indexOf(boundary,pos)-4; //waarom -4 ..? ziet er uit als linebreak spatie--boundary=-----------------------------7d21c9ae00f0
    // Stap 5 en 6..de eigelijke te uploaden file in nieuwe byte file inserten
    byte dataBytes2[] = new byte[boundaryLocation-start]; //declareren
    for (int i=0;i<(boundaryLocation-start);i++) // inserten BELANGRIJK !!
    dataBytes2=dataBytes[start+i];
    String next_id = "0";
    Statement statement = null;
    Connection conn = null;
    boolean pass = true;
    ResultSet rs = null;
    Statement stmt_empty = null;
    oracle.sql.BLOB blb = null;
    try
    int vendor = DriverUtilities.ORACLE;
    String username = ConnectionParams.userName;
    String password = ConnectionParams.passWord;
    String connStr = DriverUtilities.makeURL(vendor);
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(connStr,username, password);
    if (conn==null){pass=false;}
    } catch (Exception e){out.println("<P>" + "There was an error establishing a connection:");}
    if (pass==true)
    try
    String seq_nextval ="select forum_blob_seq.nextval from dual";
    statement = conn.createStatement();
    ResultSet rset = statement.executeQuery(seq_nextval);
    while (rset.next())
    next_id = rset.getString(1);
    if (next_id.equals("0"))
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message;
    pass = false;
    } catch (Exception e1) { out.println("Error blob1 : "+e1.toString()); };
    } // end pass
    if (pass==true)
    try
    Statement stmt2 = conn.createStatement();
    String insert_empty_blob = "INSERT INTO test_blob(id "+
    ",filename "+
    ",mimetype "+
    ",kb) "+
    "VALUES("+Integer.parseInt(next_id) +
    ",'"+saveFileName+"'"+
    ",'"+mimeType+"'"+
    ","+kb_size+")";
    stmt2.executeQuery(insert_empty_blob);
    conn.commit();
    if (stmt2!= null) {stmt2.close();}else{stmt2.close();pass = false;}
    } catch (Exception e2){
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message;
    out.println("<P>" + "2. There was an error inserting mime type:");}
    } //end pass
    if (pass==true)
    try
    conn.setAutoCommit(false);
    } catch (Exception e3) { pass = false; out.println("Error blob 3: "+e3.toString()); };
    } //end pass
    if (pass==true)
    try
    String Query_blob ="Select test_blob FROM test_blob where id="+next_id+" FOR UPDATE";
    stmt_empty = conn.createStatement();
    rs=stmt_empty.executeQuery(Query_blob);
    } catch (Exception e4) {
    pass = false;
    out.println("Error blob 4: "+e4.toString());
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message;};
    } //end pass
    if (pass==true)
    try
                             if (rs.next())
                             blb = ((OracleResultSet)rs).getBLOB(1);
                        OutputStream stmBlobStream = blb.getBinaryOutputStream();
                             try {
                                  int iSize = blb.getBufferSize();
                             byte[] byBuffer = new byte[iSize];
                             int iLength = -1;
    ByteArrayInputStream stmByteIn = new ByteArrayInputStream(dataBytes2);
                                  try {
    // while ( (iLength = in.read(byBuffer, 0,      iSize)) != -1 )
    while ( (iLength = stmByteIn.read(byBuffer, 0,      iSize)) != -1 )
                                       stmBlobStream.write(byBuffer, 0, iLength);
                                       stmBlobStream.flush();
                                       } // end while
    } catch (Exception e5) {
    pass=false;
    out.println("Error blob 5: "+e5.toString());
    message = "Uploaden mislukt !...Er ging wat fout tijdens de interactie met de database";
    responseRedirect = "/forum/uploaden.jsp?message="+message; }
                                  finally { conn.commit();     }
    } catch (Exception e6) { out.println("Error blob 6: "+e6.toString()); };
                             } //end if rs.next()
                             else {      throw new SQLException("Could not locate message record in database."); }
    } catch (Exception e7) { out.println("Error blob : "+e7.toString()); };
    } // end pass
    } // end pass2
    else //request is not multipart/form-data
    message = "Uploaden mislukt !...Gegevens niet verstuurd via multipart/form-data.";
    responseRedirect = "/forum/error.jsp?message="+message;
    out.println("Request not multipart/form-data.");
    catch(Exception e)
    try
    //print error message to standard out
    out.println("Error in doPost: " + e);
    //send error message to client
    out.println("An unexpected error has occurred.");
    out.println("Error description: " + e);
    }catch (Exception f) {}
    response.sendRedirect(responseRedirect);
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doPost(request,response);
    Regards
    Martin

  • How to add an image to combo box model in java

    i want to display a images.for that i take a combox.in that i want to add al images those i want to display, while clicking the image in combo box the image will be display.there is no problem for displaying an image, but i dont know how to add
    an image to a combo box model in net beans. please help me. if u have any idea plese forward to this mail
    [email protected]

    Hi Thomas,
                     You need to create an image field and in the source choose 'graphic content ; give the name of the variable which has the binary data . and give the type as 'MIME/image'.

  • How to add an image to an IMAGE control in Java WebDynpro

    hi
    How to add an image to an IMAGE control in Java WebDynpro.
    Please give me the steps to assign an image to an IMAGE control.
    Advanced Thanks
    brahma

    Thank You Mathan MP,
    i tried these steps, but whenever i selected the source property of image UI control, it opens a context window, but this context window does't contain any thing for selection.
    so how to solve this problem ?
    the link whatever u provided is not opened, please send the correct link.
    http://127.0.0.1:1284/help/index.jsp?topic=/com.sap.devmanual.doc.user/f3/1a61a9dc7f2e4199458e964e76b4ba/content.htm
    Thanks in Advance
    brahma

  • How to add an image in multiple pages?

    Hi,
    First be aware that before posting this, I digged into Google but could not find a solution.
    How to add an image in the footer section of a PDF document of size, say, 500pages? I am not going to add it one by one in very page, it's too time consuming.
    Is there a way to add it in the footer section or any other alternative, so that I end up with the same image in an exact position in all 500 pages?
    Thanks for your reply
    Best,
    Eric

    Answer:
    Answer: http://forums.adobe.com/message/3437269#3437269

  • How to add an image over another using af:image

    How to add an image over another using af:image
    Thanks,
    Veera

    i have a image which is black strip. i have added that to af:image
    <af:image source="image1" id="image" />
    on the black strip, i need to add company logo.
    how to achieve it.
    Thanks,
    Veera.

  • How to add some image in adobe muse

    hi.. im just new in adobe muse .. im sorry for this very noob question.. i just want to ask how to add some image in adobe muse ?? with a link .. thanks

    To add images press CTRL+D and then select the image and place it where you want.
    To hyperlink it go to the top menu and there should be Hyperlink folowed by a box. Enter your URL to link in there.
    You can also use the slideshow widget should you want to make a slideshow.

  • How to add multiple images in jinternalframe

    Hi all,
    how to add multiple images to the jinternalframe, at specified location of the pane and resizing the images with specified height and width.
    code examples are highly appreciated.
    Thanks & Regards,
    Abel

    Thanks, it works perfectly. It's a really smart way of fixing the problem too :)
    I also found your toggle button icon classes which is something I've also had a problem with.
    Thanks.

  • What code can i use to add an image to a JPanel?

    I tried multiple image tutorials and none of those supplied me with a way to add an image to a JPanel without using hidious code. Don't anyone know simpler code which i can use?

    Don't anyone know simpler code which i can use?Simpler than what? Post what you've got at the moment. Use code
    tags as described here: http://forum.java.sun.com/help.jspa?sec=formatting
    About the simplest I can think of is to make a JLabel using the
    constructor that takes an Icon argument, and then add it to the JPanel.
    (The Swing forum is the best place for this.)

  • How to add external images onto a control and still be able to resize

    Hello,
    I'm a LabVIEW newbie.  I'm trying to customize the appearance of my VIs, and one of the things I like to do is to import external image and paste it onto the faceplate of the gauge indicator.  I've followed the instruction in the Labview application note using the control editor and was able to paste the picture into indicator.  But when I use it in the front panel and resize the gauge indicator, the image (added as a decoration) doesn't resize together with the indicator.  My questions are:
    1. How to add external images onto a control/indicator and still be able to resize the image automatically when I resize the control/indicator?
    2. How to "add" a new part to an existing control/indicator?  It looks like I can only customize/modify the existing parts of the control/indicator in the control editor. 
    Any help is appreciated.  Thanks.

    1/ Do not use the image as an added decoration. Instead replace part of the control with the image. Tis is illustrated in the attached vi : the arrow was pasted as a decoration, and also used to replace the slide cursor. Changing the control size do not affect the decoration, but changes the cursor.
    2/ What do you mean by adding new parts to a control. We have just seen that it was possible to modify a control. Now, if you want to include additionnal functionnality, that's another story. You can replace parts of the control, and this can give interesting results.  You can edit a slide control, and replace the numeric indicator by another control, including a numeric indicator, that you can replace with etc...
    But there, it still the same info displayed under different forms. If you want to have several independant functions on the same control, such as a string display and a boolean and a numeric indicator, then that's a job for a cluster...
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Slide with Arrow.vi ‏13 KB

  • How to add javafx image project in my jsp page ?

    how to add javafx image project in my jsp page ?

    Create your JavaFX application as an Applet... then embed the applet object inside your html. I'm sure if you create a javafx netbeans project and hit build... you get a html file that shows you how to load the built binary output into the page.

  • How to add a image to header of exporting pdf in devexpress gridview

    hi guys ;
    how to add a image to header of exporting pdf in devexpress gridview content

    Hi Aly14,
    I am not sure what the type of your project was, is it a C# project or an asp.net project?
    If would be helpful if you could share us more information about your issue.
    In addition, I made a research about your issue and I think the links below might be useful to you:
    # ASPxGridView insert an image for Header and Footer sections for pdf export
    https://www.devexpress.com/Support/Center/Question/Details/Q37155
    # Adding an "Export Header" to PDF export in MvcGridView
    https://www.devexpress.com/Support/Center/Question/Details/T141918
    Best Regards,
    Edward
    This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore,
    Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you
    completely understand the risk before retrieving any software from the Internet.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

  • How can add a images file  to anothere image file

    hi
    Requirement is: i have one image in data base , i is show to user in my application
    know we want add another image file in to a current image file (just append)
    at end .
    i was tried with following code below
    i was read the previous(Old) image content from the data base and placed into c:\\ReArchive\\test_content.tiff
    ResultSet rs2=dbBean.getSQLRows("select binarycontent from ContentVersion where contentindex="+IndexValue+"");
    byte[] bTempData_content=new byte[65536];
    while(rs2.next()){              
    File f = new File("c:\\ReArchive\\test_content.tiff");
    f_content.delete();
    f_content.createNewFile();
    FileOutputStream dest_contentVersion = new FileOutputStream(f_content);
    while(rs2.next()){              
    InputStream is_content=rs2.getBinaryStream("Binarycontent");
    nActualRead_content=is.read(bTempData_content,0,65536);
    while(nActualRead_content>0)
    dest_contentVersion.write(bTempData_content,0,nActualRead_content);
    nActualRead_content=is.read(bTempData_content,0,65536);
    Then i was took New image file from data base and place in to c:\\ReArchive\\test.tiff");
    int nActualRead=0;
    ResultSet rs1=dbBean.getSQLRows("select * from Object_Store where Barcode_ID='"+strBar_Code+"'");
    byte[] bTempData=new byte[65536];
    File f = new File("c:\\ReArchive\\test.tiff");
    f.delete();
    f.createNewFile();
    FileOutputStream dest = new FileOutputStream(f);
    while(rs1.next()){
    InputStream is=rs1.getBinaryStream("Obj_Content");
    nActualRead=is.read(bTempData,0,65536);
    while(nActualRead>0)
    dest.write(bTempData,0,nActualRead);
    nActualRead=is.read(bTempData,0,65536);
    then i tried add two images by converting InputStream to String and i am trying add to images
    but i was failed ,i think i am in not correct way , how can i solve this problem
    thanks advance
    gss

    Don't you think it would be a good idea to tell us how you failed?

Maybe you are looking for