Swing application w/images

Hello,
Java Image I/O provides ways to load and save images into swing applications. Does anyone know of other APIs? We're using Spring/RMI with a Swing client. The images would be stored on the server by index or something. Whats the best approach to write such an application? something that will provide the most flexibility (multiple image formats... viewing, saving, printing etc.) . thanks

Thanks for the response. Can i incorporate the ability to view TurboCad sketches (.tcw files) using this API?

Similar Messages

  • Open image in Swing Application

    Hi,
    I'm having trouble getting an image to open into my swing application and I cant figure out whats wrong. In response to selecting the "Open" button or menu item a JFileChooser opens up and i select an image but the image doesn't actually load. If anyone could help i'd really appreciate it.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.border.*;
    import javax.imageio.*;
    class PhotoEditor extends JPanel implements ActionListener {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        JMenu imageMenu, effectsMenu;
        JFileChooser fc = new JFileChooser();
        BufferedImage img = null;
           public JMenuBar createMenuBar() {     
         JMenuBar menuBar = new JMenuBar();
        /* Build the first menu: */
        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        //a group of JMenuItems under the File option:
            String[] menuItems1 = {"Open", "Save","Save As..", "Close"};
        String[] menuIcons1 = {"Open.gif", "Save.gif", "", ""};
        for (int i = 0; i<menuItems1.length; i++)
                  JMenuItem fileMI = new JMenuItem(menuItems1, new ImageIcon(menuIcons1[i]));
              fileMI.addActionListener(this);
              fileMenu.add(fileMI);
    //adding a separator to the drop down menu list
    fileMenu.addSeparator();
    JMenuItem exitMI = new JMenuItem("Exit", new ImageIcon("Exit.gif"));
    exitMI.addActionListener(this);
    fileMenu.add(exitMI);
    /* Code which builds all the menu here */
    return menuBar;
         public JToolBar createToolBar() {     
         JToolBar toolB = new JToolBar(FlowLayout.LEFT);
    toolB.setLayout(new FlowLayout());
    // contentPane.add(toolB, "North");
    JButton newButton = new JButton(new ImageIcon("new24.gif"));
    newButton.addActionListener(this);
    toolB.add(newButton);
    newButton.setToolTipText("New");
    newButton.setActionCommand("New");
    //adding a separator to the drop down menu list
    toolB.addSeparator();
    JButton openButton = new JButton(new ImageIcon("open24.gif"));
    openButton.addActionListener(this);
    toolB.add(openButton);
    openButton.setToolTipText("Open");
         openButton.setActionCommand("Open");
    /* More code building the toolbar*/
    return toolB;
         public void actionPerformed(ActionEvent e) {
    Object eventSource = e.getSource();
    if ((eventSource instanceof JMenuItem) || (eventSource instanceof JButton));{
    String label = (String) e.getActionCommand();
    //Sets up the Action Listeners
    if (label.equals("Exit")) {
    System.exit(0);
    // Closes application
    else if (label.equals("Open")) {
         openImage();
    /* More codes for each button or menu item */
    protected void openImage() {
              int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
         try {
                   img = ImageIO.read(file);
                        catch (IOException e1) {
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
    g.drawImage(img, 500, 500, null);
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Photo Editor");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create a main label to put in the content pane.
    JLabel main = new JLabel();
    // main.setOpaque(true);
    // main.setBackground(new Color(128, 128, 128));
    main.setPreferredSize(new Dimension(800, 600));
    //Set the menu bar and add the label to the content pane.
    PhotoEditor mainmenu = new PhotoEditor();
    frame.setJMenuBar(mainmenu.createMenuBar());
         frame.getContentPane().add(mainmenu.createToolBar(), BorderLayout.PAGE_START);
    frame.getContentPane().add(main, BorderLayout.CENTER);
    //Display the window.
    frame.pack();
    frame.setVisible(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();

    Your PhotoEditor class extends JPanel. In that class you override paintComponent(). But you never add the panel to the GUI, so that method is never invoked.
    Personally I would have the PhotoEditor class extend JFrame. Then in the constructor you build all the components for the frame
    a) build the menu
    b) build the toolbar
    Then I would create a PhotoPanel class that you extend and override the paintComponent(). Then you add this panel to the GUI as your main panel.
    For a simple example of drawing a background image on a panel search the forum for my BackgroundImage example.

  • Displaying image on the swings application

    Hi All,
    I want to display images onto my swing application. I was using ImageIcon and Class to getResource(filename). It can only provide me images that i have placed in my package not outside my package.
    Please help me, how to to do?
    Thanks in advance.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html]How to Use Icons

  • Including images in JAR for Swing Application

    I am using a couple of images in a Swing application. When I create the JAR file I include all the images. The JAR executes fine but the images are missing. When I put the images in the same directory as the JAR file the images are properly displayed.
    The code I use to display the images is:
    JLabel label = new JLabel(new ImageIcon("pleaseWait.gif"));
    Can anyone let me know what I need to do to get the image from the JAR? Do I need to look at ResourseBundle's?
    Thanks for any help..

    Does anybody know what is the reason of my problem??
    I created a package called test in my eclipse env. and in that package I placed folder named graph in which there is a file Help.png.
    Here is all the code I run in eclipse and it runs properly. When I create a jar file (using eclipse wizard) to execute without eclipse it can not execute and shows nothing (process starts and I have to kill it by myself in OS). Maybe there is some mistake with making jar... I do not know
    So let someone try tu run my class or build jar file and try to execute and share his observations (solutions) ??
    package test;
    import java.awt.Toolkit;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    public class TestWindow extends JFrame {
         private JButton jButton1 = new JButton(new JARImage().getImage("Help.png"));
         public TestWindow() {
              this.getContentPane().add(jButton1);
              this.validate();
              this.setVisible(true);
         private class JARImage {
              protected ImageIcon getImage(String imageName) {
                   ImageIcon image = new ImageIcon();
                   try {
                        image.setImage((Toolkit.getDefaultToolkit().getImage(getClass()
                                  .getResource("graph/" + imageName))));
                   } catch (Exception ex) {
                        System.out.println("Image Error: " + ex);
                        ex.printStackTrace();
                   return image;
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              new TestWindow();
    }

  • Image resize problem in Swing Application

    Hi All
    I need a help on resizing and adjustment of Image in Swing application.
    I am developing a Swing Application. There I am displaying a image on header.
    I am finding it difficult to manage the image, as I want the image to perfectly fit horizontal bounds(Even on window resize).
    The current code given below is unable to do so.. Even it's not able to fit the horizontal bounds by default.
    ========================================
    //code for image starts
            BufferedImage myPicture;
            JLabel picLabel = null;
            try {
                 myPicture = ImageIO.read(new File("artes_header.png"));
                    picLabel = new JLabel(new ImageIcon(myPicture));
              } catch (Exception e) {
            GridBagLayout gLayout = new GridBagLayout();
            getContentPane().setLayout(gLayout);
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 1;
            c.weightx = 1;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(0, 0, 0, 0);
            panelTop.setBackground(Color.white);
            getContentPane().add(picLabel, c);
            c.gridx = 1;
            c.gridy = 2;
            c.weightx = 1;
            c.weighty = 1;
            getContentPane().add(tabPane, c);========================================
    Kindly anyone help me solve the same issue.
    Many thanks in advance.
    Regards,
    Gaurav
    Edited by: user7668872 on Jul 31, 2011 6:25 AM
    Edited by: user7668872 on Aug 4, 2011 3:56 AM

    Your questions doesnt make a whole lot of sence so not sure if this is what you want...
    This is a class to display an image on a jpanel. You can then use layout managers to make sure it is centrally alligned
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.*;
    class testImagePanel{
        public static void main(String[] args){
            BufferedImage image = null;
            ImagePanel imagePanel = null;
            try{
                image = ImageIO.read(new File("image.jpg"));
                imagePanel = new ImagePanel(image);
                imagePanel.setLayout(new BorderLayout());
            }catch(IOException  e){
                 System.err.println("Error trying to read in image "+e);
            JFrame frame = new JFrame("Example");
            frame.add(imagePanel);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);               
    public class ImagePanel extends JPanel {
        private BufferedImage image;
        private Dimension size;
        public ImagePanel(BufferedImage image) {
            this.image = image;
            this.size = new Dimension();
            size.setSize(image.getWidth(), image.getHeight());
            this.setBackground(Color.WHITE);
        @Override
        protected void paintComponent(Graphics g) {
            // Center image in this component.
            int x = (getWidth() - size.width)/2;
            int y = (getHeight() - size.height)/2;
            g.drawImage(image, x, y, this);
        @Override
        public Dimension getPreferredSize() { return size; }
    }

  • I want to implement thems functionality in  my swing application

    Hi All...
    I want to implement the themes object in my swing application,How ,where to start and move that functionality,If anybody use this functionality in your program experience can u share with me.
    Than to Advance
    ARjun...

    Hi Kuldeep Chitrakar
    I can do that in web intelligence. dont want that
    I am replicating some of the sample report of SQL Servers in BusinessObjects XI R3.1.
    One of the SQL Sever's report is of product catalogue type that gives complete information like name, category, description along with the products image etc... for each of the products.
    I am trying to replicate the above said SQL Server report in Business objects XI R3.1. I am facing problem in bringing the image in to my BO report. The image resides in a table and its datatype is of varbinary(max). I don't know the exact matching while creating an object in the uiverse designer.
    Here is the url link http://errorsbusinessobjectsxir3.blogspot.com/2010/10/business-objects-image-errors.html
    Regards
    Prasad

  • JNLP - Swing application compiled in jdk1.5 not working in jdk1.6

    I have one swing application, compiled in jdk 1.5 and deployed in JNLP with jdk 1.5. When client machine try to access the application and having jre 1.5 then it works fine. but if client machine having jre 1.6 or version greater than 1.5 then application does not work properly.
    Please help me, i got stuck and not able to solve the problem.
    this is my JNLP
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+" codebase="http://10.1.1.145:8080/uttimesheet" href="launch.jnlp">
    <information>
    <title>TimeSheet Portal</title>
    <vendor>Geometric Global</vendor>
    <description>A simple java desktop application based on Swing Application Framework</description>
    <description kind="short">TimeSheet Portal</description>
    <homepage href="http://appframework.dev.java.net"/>
    </information>
    <security>
    <all-permissions/>
    </security>
    <resources>
    <j2se version="1.5+" />
    <jar href="UTTimeSheet.jar" main="true" download="eager"/>
    <jar href="lib/antlr-2.7.5H3.jar" download="eager"/>
    <jar href="lib/appframework-1.0.3.jar" download="eager"/>
    <jar href="lib/asm.jar" download="eager"/>
    <jar href="lib/cglib-2.1.jar" download="eager"/>
    <jar href="lib/commons-collections-2.1.1.jar" download="eager"/>
    <jar href="lib/commons-logging-1.0.4.jar" download="eager"/>
    <jar href="lib/dom4j-1.6.jar" download="eager"/>
    <jar href="lib/hibernate3.jar" download="eager"/>
    <jar href="lib/jta.jar" download="eager"/>
    <jar href="lib/log4j-1.2.9.jar" download="eager"/>
    <jar href="lib/poi-3.0.2.jar" download="eager"/>
    <jar href="lib/postgresql-8.3-603.jdbc3.jar" download="eager"/>
    <jar href="lib/swing-layout-1.0.3.jar" download="eager"/>
    <jar href="lib/swing-worker-1.1.jar" download="eager"/>
    <jar href="lib/swingx-0.9.2.jar" download="eager"/>
    </resources>
    <application-desc main-class="timesheetproject.TimeSheetProjectApp">
    </application-desc>
    </jnlp>
    Thanks in Advance.

    Thanks Luca for your time,
    we have deployed application in tomcat and changed the home page of tomcat to our application home page(html page). and url is http://10.1.1.145:8080/
    Application home page contain link to jnlp. so whenever user click on link (in home page) then jnlp will execute and launch the swing application.
    do you need some more clarification?
    below is the home page(html).
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>Launch TimeSheet Portal via JNLP</title>
    </head>
    <body>
         <center>
              <br>
              <img src="images/Geo-logo.JPG" />          
              <br>
              <hr width="70%" />
              <br>
              <table width="70%">
                   <tr><td> </td></tr>
                   <tr>
                        <td colspan="2" align="center">
                             <align="center">
                                  <h2>Welcome to TimeSheet Portal.</h3>
                             </align>
                        </td>
                   </tr>
                   <tr><td> </td></tr>
                   <tr><td> </td></tr>
                   <tr>
                        <td align="center">
                             <align="center">
                                  <h3><u>Live Sites:</u></h3>
                             </align>
                        </td>
                        <td align="center">
                             <align="center">
                                  <h3><u>Demo Sites:</u></h3>
                             </align>
                        </td>
                   </tr>
                   <tr>
                        <td width="50%" align="center">
                             <img src="images/launchPortal.png" onmouseover="this.src='images/launchPortalMouseOver.png';" onmouseout="this.src='images/launchPortal.png';" border="0"/>          
                             <br><br>
                             <img src="images/launchAdminPortal.png" onmouseover="this.src='images/launchAdminPortalMouseOver.png';" onmouseout="this.src='images/launchAdminPortal.png';" border="0"/>          
                        </td>
                        <td width="50%" align="center">
                             <img src="images/demoPortal.png" onmouseover="this.src='images/demoPortalMouseOver.png';" onmouseout="this.src='images/demoPortal.png';" border="0"/>
                             <br><br>
                             <img src="images/demoAdminPortal.png" onmouseover="this.src='images/demoAdminPortalMouseOver.png';" onmouseout="this.src='images/demoAdminPortal.png';" border="0"/>
                        </td>
                   </tr>
                   <tr><td> </td></tr>
                   <tr><td> </td></tr>
         </table>
         <table width="70%">
              <tr><td> </td></tr>
              <tr><td> </td></tr>
              <tr><td align="center">
                   FAQ   |  
                   Help   |  
                   Why Timesheet   |  
                   Report a bug   |  
                   Contact Us   |  
    Subtask Mapping   
              </td></tr>
         </table>
         <br><br><br><br>
         <table width="70%" bgcolor="#C0C0C0" style="vertical-align: bottom">
              <tr>
                   <td colspan="2" align="center" style="vertical-align: bottom" bgcolor="#C0C0C0">
                        ©<font size="1.5" face="Verdana"> 2008 Geometric Ltd. All rights reserved.<br>
                             Best optimized for a resolution of 1024 and above. JRE 1.5 is a pre-requisite                          for using these applications.
                        </font>
                   </td>
              </tr>
         </table>
         </center>
    </body>
    </html>
    Thanks.

  • How to send byte array and String values to servlet from Swing application

    Hi all,
    I am new to swing, servlet, and socket connection.
    I have swing application to draw images and some input data. I dont know to send to server.
    byte[] buf = baos.toByteArray();
    URL servletURL = new URL("http://10.70.70.1:8080/servlet/SaveImage)
    URLConnection conn = servletURL.openConnection();
    conn.setDoOutput(true);
    BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
    out.write(buf&a=aaaa&b=bbbbb);
    out.flush();
    out.close();
    can I do like this. Strings are received in server side perfect. but i cant get byte array data. Please help me.
    Thanks in advance.

    <img src="myservlet">
    In your myservlet:
    response.setContentType("image/jpeg");
    then write your image date via ImageIO that uses response output stream.

  • BackGround picture for a Swing application??

    hi,
    once I got a nice idea while watching some webpages. we can give a background picture for a webpage in <body> tag?
    I want to do same thing for any Swing application. Currently I am working on that issue. Any suggestions are welcome!!
    santhosh

    Hi everybody!
    Finally I got it. now Using this We can enable background for any swing application.
    the complete code is shown here. If you have any problems regarding this code, please mail to [email protected]
    /******************************[TexturedImageIcon.java]***********************/
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    /* this is used to generate a tiled image from a given image file.*/
    public class TexturedImageIcon extends ImageIcon
         private Dimension size = new Dimension(10, 10);
         BufferedImage bimg1,bimg;
         Graphics2D g2;
         ComponentListener cl = new ComponentAdapter(){
              public void componentResized(ComponentEvent ce){
                   Component c = (Component)ce.getSource();
                   size = c.getSize();
                   createImage();
         public void setImage(String filename){
              super.setImage(new ImageIcon(filename).getImage());
              bimg1=null;
              createImage();
         public TexturedImageIcon(Component comp, Image img){
              super(img);
              addListener(comp);
         public TexturedImageIcon(Component comp, String filename){
              super(filename);
              addListener(comp);
         public TexturedImageIcon(Component comp, URL url){
              super(url);
              addListener(comp);
         private void addListener(Component comp){
              comp.addComponentListener(cl);
         private void createImage(){
              bimg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
              g2 = bimg.createGraphics();
              Rectangle2D rect = new Rectangle2D.Float(0,0,size.width-1, size.height-1);
              Rectangle2D tr = new Rectangle2D.Double(0,0,super.getIconWidth(), super.getIconHeight());
              if(bimg1==null){
                   bimg1 = new BufferedImage(super.getIconWidth(), super.getIconHeight(), BufferedImage.TYPE_INT_RGB);
                   Graphics2D g = bimg1.createGraphics();
                   g.drawImage(super.getImage(), null, null);
              TexturePaint tp = new TexturePaint(bimg1, tr);
              g2.setPaint(tp);
              g2.fill(rect);
         public int getIconWidth(){ return size.width; }
         public int getIconHeight(){ return size.height; }
         public Image getImage(){
              System.out.println("asked");
              return bimg;
         public void paintIcon(Component c, Graphics g, int x, int y){
              Graphics2D g2d =(Graphics2D)g;
              g2d.drawImage(bimg, null, null);
         public static void main(String[] args){
              JFrame f = new JFrame();
              f.setSize(300,300);
              JLabel label = new JLabel();
              label.setBackground(Color.white);
              label.setBorder(BorderFactory.createRaisedBevelBorder());
              label.setIcon(new TexturedImageIcon(label, "world2.gif"));
              f.getContentPane().setLayout(new BorderLayout());
              f.getContentPane().add(label, BorderLayout.CENTER);
              f.show();
    /*********************************[JFCUtils.java]************************/
    /*The main logic to enable background picture lies in this class*/
    public class JFCUtils{
         public static ContainerListener cl = new ContainerAdapter(){
              public void componentAdded(ContainerEvent ce){
                   JComponent child = (JComponent)ce.getChild();
                   child.setOpaque(false);
                   child.addContainerListener(this);
                   addlisteners(child);
         public static TexturedImageIcon enableBackGround(JFrame f, String filename){
              ((JPanel)f.getContentPane()).setOpaque(false);
              JLayeredPane lp = f.getLayeredPane();
              JLabel label = new JLabel();
              TexturedImageIcon icon = new TexturedImageIcon(label, filename);
              label.setIcon(icon);
              JPanel panel = new JPanel(new BorderLayout());
              panel.add(label, BorderLayout.CENTER);
              lp.add(panel, new Integer(Integer.MIN_VALUE));
              Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
              panel.setBounds(0, 0, screen.width,screen.height);
              addlisteners((JComponent)f.getContentPane());
              return icon;
         private static void addlisteners(Component c){
              c.toString();
              if(c instanceof JComponent) ((JComponent)c).setOpaque(false);
              if(c instanceof Container){
                   Container ct = (Container)c;
                   ct.addContainerListener(cl);          
              for(int i=0; i<ct.getComponentCount(); i++){ //recursivly make all subcomponents transparent
                   Component child = (Component)ct.getComponent(i);
                   addlisteners(child);
         public static void main(String[] args){
              JFrame f = new JFrame();
              enableBackGround(f, "bg.jpg");
              JButton b = new JButton("fdfdfdfd");
              f.getContentPane().add(b, BorderLayout.NORTH);
              f.setSize(300,300);
              f.show();
    /*************************************[UserDialog.java]**************************/
    //to check how a swing application with background looks like
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class UserDialog extends JDialog
         JPanel contents = (JPanel)getContentPane();
         JTextField shortField = new JTextField(20);
         JTextField nameField = new JTextField(20);
         JTextField emailField = new JTextField(20);
         JTextField smtpServerField = new JTextField(20);
         JTextField pwdField = new JPasswordField(20);
         JTextField pwdField1 = new JPasswordField(20);
         boolean okay = false;
         public UserDialog(JFrame owner){
              super(owner, "New User Details", true);
              initComponents();
              pack();
              setResizable(false);
         public UserDialog(JDialog owner){
              super(owner, "New User Details", true);
              initComponents();
              pack();
              setResizable(false);
         private void initComponents(){
              JPanel west = new JPanel(new GridLayout(0, 1));
              west.add(new JLabel("Short Name"));
              west.add(new JLabel("Full Name"));
              west.add(new JLabel("Email"));
              west.add(new JLabel("SMTP Server"));
              west.add(new JLabel("Password"));
              west.add(new JLabel("Confirm Password"));
              JPanel east = new JPanel(new GridLayout(0, 1));
              east.add(shortField);
              east.add(nameField);
              east.add(emailField);
              east.add(smtpServerField);
              east.add(pwdField);
              east.add(pwdField1);
              JPanel south = new JPanel();
              JButton ok = new JButton("Ok");
              JButton cancel = new JButton("Cancel");
              south.add(ok);
              south.add(cancel);
              contents.setBorder(JFCUtils.border);
              contents.setLayout(new BorderLayout(10, 10));
              contents.add(west, BorderLayout.WEST);
              contents.add(east, BorderLayout.EAST);
              contents.add(south, BorderLayout.SOUTH);
              ActionListener al = new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        okay = ae.getActionCommand().equals("Ok");
                        setVisible(false);
              ok.addActionListener(al);
              cancel.addActionListener(al);
         private void clearFields(){
              shortField.setText("");
              nameField.setText("");
              emailField.setText("");
              smtpServerField.setText("");
              pwdField.setText("");
              pwdField1.setText("");
         public User getUser(){
              clearFields();
              okay = false;
              show();
              if(okay) return new User(shortField.getText(), nameField.getText(), emailField.getText(), smtpServerField.getText(), pwdField.getText());
              else return null;
         public static void main(String[] args){
              Dialog dlg = new UserDialog();
              TexturedImageIcon ticon = JFCUtils.enableBackGround(f, "bg.jpg");.show();
              //we can change the background picture by calling ticon.setImage(...) at runtime.

  • Memory Leak in a multi threaded Swing application  (ImageIcon)

    When I profile my swing application with netbeans 5.5 , I notice that after each periodically tidy up my image container (add,remove IconImage objects to a hashmap or arraylist), there gather by and by surviving objects. This leads to run out of memory after a while. Is there any other way to avoid this effect?
    Any ideas about "The JVM is notorious for caching images."
    please help..
    what I have made briefly:
    1.) Read the binary stream from the db :
    rs=stmt.executeQuery(query);
    if(rs.next()){
        int len=rs.getInt(2);
        byte [] b=new byte[len];
        InputStream in = rs.getBinaryStream(3);
        try {
                in.read(b);
                in.close();
                img=Toolkit.getDefaultToolkit().createImage(b);
         } catch (IOException e) {
                e.printStackTrace();
    stmt.close();
    rs.close();2.) hold the icon as field :
    this.icon =  new ImageIcon(img);3.) After a while I remove the object from my collection and on the
    overridden method finalize() I also call the flush() method.
    if(this.icon != null){
                this.icon.getImage().flush();
                this.icon = null;
    }The surviving objects still increase?! On the page of SUN they
    submitted a bug. But this is set on closed/fixed.
    (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4014323)
    What am I doing wrong? I also use the byte[] constructor on creating the icon and
    my java version is 1.5.0_10.

    If in your JFrame u have placed your image, before invoke the dispose()
    method put explicitly the image pointer to null and deregister all listener
    you have added to any componentI implemented your suggest and after starting a long time test, in one hour there gathered aprox. 500 surviving generations. I attach a snapshot and the java file ( http://www.box.net/public/eqznamrazd ). The used heap size swings between 3MB and 5MB. I guess this wont kill so quickly the application but anyway there is something wrong!
    Even properly closed streams, database connections etc.. Really despairing. Could one take a look to the java source?
    some snippets bellow:
    private class MyImageIcon extends ImageIcon {
            public MyImageIcon(Image img){
                super(img);
            public void removeImage(Image anImage){
                tracker.removeImage(anImage);
    private class DetailDialog extends javax.swing.JFrame {
            private String personnr;
            private MyImageIcon icon;
            public DetailDialog(String personnr,MyImageIcon icon){
                this.personnr = personnr;
                this.icon = icon;
            public void dispose() {
                if(icon != null){
                    icon.removeImage(icon.getImage());
                    icon.getImage().flush();
                    icon = null;
                super.dispose();
    private class Person extends Object {
            private MyImageIcon icon;
            private String number;
            private DetailDialog detailDialog;
            protected void destroy() {
                if(icon!=null){
                    icon.removeImage(icon.getImage());
                    icon.getImage().flush();
                    icon = null;
                if(detailDialog!=null){
                    detailDialog.dispose();
    private Image LoadImageFromDB(String personnr){
            Image img = null;
            String filename = personnr + ".jpg";
            Connection con = getMysqlConnection();
            Statement stmt;
            ResultSet rs;
            try {
                stmt = con.createStatement();
                String query = "select * from personImage where image='"+filename+"'";
                rs=stmt.executeQuery(query);
                if(rs.next()){
                    int len=rs.getInt(2);
                    byte [] b=new byte[len];
                    InputStream in = rs.getBinaryStream(3);
                    try {
                        in.read(b);
                        in.close();
                        img =
                                java.awt.Toolkit.getDefaultToolkit().createImage(b);
                    } catch (IOException e) {
                        e.printStackTrace();
                rs.close();
                rs = null;
                stmt.close();
                stmt = null;
                con.close();
                con = null;
            } catch (SQLException e) {
                e.printStackTrace();
            return img;
    public void random(){
            java.sql.ResultSet rs = null;
            java.sql.Statement stmt=null;
            java.sql.Connection con = getSybaseConnection();
            try {
                try {
                    stmt = con.createStatement();
                    rs = stmt.executeQuery(randomquery);
                    while(rs.next()){
                        Person person = new Person();
                        person.number = rs.getString("PersonNr");
                        Image img = LoadImageFromDB(person.number);
                        if(img !=null){
                            MyImageIcon ico = new MyImageIcon(img);
                            person.icon = ico;
                        person.detailDialog = new
                                DetailDialog(person.number,person.icon);
                        personList.add(person);
                        System.out.println("Container size: " +
                                personList.size());
                        counter++;
                    if(counter%20 == 0){
                        for(Person p : personList){
                            p.destroy();
                        personList.clear();
                        System.gc();//no need, but I force for this example
                        System.out.println("Container cleared, size: " +
                                personList.size());
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }finally{
                    if(rs != null){
                        rs.close();
                    }if(stmt != null){
                        stmt.close();
                    }if(con != null){
                        con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
        }

  • JMS in Swing Application ?

    Hi All,
    I have one scanning application.In which i will scan images and do some processing as per my need.But the scanner which i am using is very fast in scanning pages having speed is 80 pages per minutes.As scanner scan paper application start new thread which will take image and process it. Number of thread increase as the scanner scan images because of time take for processing is more (in fraction of seconds).
    So tackle this problem i have decide to use some kind on message queue like MSMQ in microsoft.I got suggestion that there is JMS in java.I don't know much about JMS.My question is,
    Is we can implement JMS in my Swing Application?
    If yes,then how can we (please some idea)?
    Please It's very urgent for my project.Please Give some idea?
    Thanks in Advance
    AP_java

    assuming that all the work you need to do is in the same process, you do not need JMS. instead, you want to use a thread pool. JMS is only necessary if you are sending messages between different processes.
    basically, just create a thread pool with a max number of threads, and submit a job to it for each image.

  • Performance technique on Swing application

    Can some one tell me whats the performance technique i should have to follow on any Swing application or Database centric Swing application?
    If i have huge amount of data which is coming from database and that data displaying in table format in Swing application. So, what performance technique i have to follow to improve the performance of Swing application?

    Encephalopathic wrote:
    good guess. What do you think? Loading the images in the painting methods?That is a common mistake. To the OP, some common errors when overriding paintComponent include:
    1. Loading an image each time paintComponent() is called. Just load it once, cache it, and only draw it in paintComponent, this saves you from the IO of loading the image on repaints.
    2. Doing application logic/complex operations in paintComponent. paintComponent should be kept fast, only do painting operations, keep long-running tasks, IO, etc. out of it.
    3. To a lesser extent, doing lots of complex painting on a repaint call, maybe lots of transforms, translucency, xor-ing, whatever. For most common painting (at least in my work, YMMV), this isn't a problem, but if it is you should consider drawing all "static" stuff to a buffer (such as a BufferedImage) and just painting the BufferedImage, as opposed to drawing all the static stuff each paintComponent call.
    The idea is just to keep the painting logic as fast as possible, to avoid slow repaints as you're seeing. Sometimes people don't realize that paintComponent() will be called every time your component needs to be even partially repainted (minimized/maximized window, partially hidden by another window then revealed again, stretched by window resizing, etc.). That's why things like IO are out of the question.
    Of course, I'm babbling now. This may not even be your problem, or you may already know all this stuff. If so, just ignore this post!

  • Performance issue on swing application

    Hi,
    I have one swing application and i am facing one performance issue after minimizing the applicaton. The same application is taking 2-5 seconds to redraw the screen again when i am trying to maximize it. Is there any way to improve this redraw delay ?..Is there any way to tweak the Event Dispatcher thread and by this we can overcome correct me if i am wrong? .
    Is there anybody facing such kind of issue please help me...
    Thanks in Advance,
    Anish.

    Encephalopathic wrote:
    good guess. What do you think? Loading the images in the painting methods?That is a common mistake. To the OP, some common errors when overriding paintComponent include:
    1. Loading an image each time paintComponent() is called. Just load it once, cache it, and only draw it in paintComponent, this saves you from the IO of loading the image on repaints.
    2. Doing application logic/complex operations in paintComponent. paintComponent should be kept fast, only do painting operations, keep long-running tasks, IO, etc. out of it.
    3. To a lesser extent, doing lots of complex painting on a repaint call, maybe lots of transforms, translucency, xor-ing, whatever. For most common painting (at least in my work, YMMV), this isn't a problem, but if it is you should consider drawing all "static" stuff to a buffer (such as a BufferedImage) and just painting the BufferedImage, as opposed to drawing all the static stuff each paintComponent call.
    The idea is just to keep the painting logic as fast as possible, to avoid slow repaints as you're seeing. Sometimes people don't realize that paintComponent() will be called every time your component needs to be even partially repainted (minimized/maximized window, partially hidden by another window then revealed again, stretched by window resizing, etc.). That's why things like IO are out of the question.
    Of course, I'm babbling now. This may not even be your problem, or you may already know all this stuff. If so, just ignore this post!

  • Best setup for a swing application

    Hello,
    I have developed an Swing application for a EPOS machine.
    The machine has around 512 ram.
    What's the best setup for me in terms of performance, for example, which JVM to use etc.....
    Cheers
    Bobby

    bsbiran wrote:
    Hi,
    Well the app require alot of images and I parts of it do run 'slow'
    ...I'm currently going through a book about Swing and read that many times the "slowness" of a Swing-application can be credited to the programmer for not using the API efficiently/correctly (letting the app repaint too much, or repainting large parts that don't need repainting at all, to name just two things). So, I don't know how much of a Swing-guru you are, but it might be better to read a few decent Swing tutorials or pick up a good Swing book.

  • Seperating Graphics from code on Swing application

    1)I want to draw simple graphics like rectangles, curves, lines, images etc on top of my swing application. I would like to separate the graphic representation from the code to an external file like XML,XAML , SVG etc.. All these graphics should be editable(i.e. scaling, translating the position, changing font, color etc) . Please let me know the possible technologies?
    2)Also is it possible to use HTML5 canvas component oj java swing.
    JButton button = new JButton("<html><canvas>...</canvas></html>")
    is this possible?.It is not working for me, if it is possible am i missing out something?

    Hi,
    Thanks for your reply!
    I went through the link you provided. This is exactly how my application draws graphics now. But my problem is one of my shape will be a rectagle with circle, another will be rectangle with image.So i have to write seperate classes to draw each of these shapes. My idea is to avoid creating seperate classes but an external file will define all the graphics components and library should be smart enough to identify the drawings required and paint it on my swing components. I am in search for a library or a java feature that can do this. Please help!
    Regards,
    Anjana

Maybe you are looking for