Thread problem in swing application?

Hi,
I have a doubt in GridLayout and Threads. I�m doing one small application which is accepting images and Alphabets. Actually, What I�m doing running images and alphabets(combinedly) in frequent intervals. For this I used GridLayout and Thread concept. But I have a problem in paint method. How to call the GridLayout frequently. In GridLayout , I�m putting Images and alphabets. Acutually in paint method , there are only drawString or drawImage or other methods. Is it possible to call my layout. Is so, can anybody help me in this regard. Is there any way to do it . please suggest me.
Thanks,
-Balaji
My code follows:
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.*;
import java.applet.Applet;
import java.util.*;
import java.io.*;
public class GridLayEx2 extends Applet implements Runnable {
private Random r = new Random();
private Thread imageThread = null;
GridLayout glt;
public void init() {
glt = new GridLayout(3,3);
setLayout(glt);
} // end of init method
public void start(){
if (imageThread == null) {
imageThread = new Thread(this, "GridLayEx2");
imageThread.start();
} // end of start method
public void run(){
Thread myThread = Thread.currentThread();
while (imageThread == myThread) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e){ }
}// end of run method
public void paint(Graphics g){
Font boldFont = new Font("Helvetica", Font.BOLD, 25);
Font plainDerived =
boldFont.deriveFont(Font.PLAIN, 25);
JLabel myLabel[] = new JLabel[9];
String myUrl = "C:\\Regoti\\Vision\\AP\\Project\\Version1\\images\\duke1.gif";
myLabel[0] = new JLabel(new ImageIcon(myUrl));
myLabel[1] = new JLabel("A");
myLabel[2] = new JLabel("A");
myLabel[3] = new JLabel("A");
myLabel[4] = new JLabel("A");
myLabel[5] = new JLabel("A");
myLabel[6] = new JLabel("A");
myLabel[7] = new JLabel("A");
myLabel[8] = new JLabel("A");
myLabel[1].setFont(boldFont);
myLabel[2].setFont(boldFont);
myLabel[3].setFont(boldFont);
myLabel[4].setFont(boldFont);
myLabel[5].setFont(boldFont);
myLabel[6].setFont(boldFont);
myLabel[7].setFont(boldFont);
myLabel[8].setFont(boldFont);
int values[] = new int[9];
values = gen_pos_uni_ran_num(0,8);
for(int i = 0; i < 9; i++)
add(myLabel[values]);
} // end of paint method
public void stop(){
imageThread = null;
} // end of stop method
public int[] gen_pos_uni_ran_num(int min, int max)
int results[] = new int[Math.abs(max - min) + 1];
for(int i = 0; i < results.length; ++i)
results = -1;
outer_loop:
for(int i = 0; i < results.length; ++i)
int random_int = (int)((Math.random() * results.length) + min);
for(int j = 0; j < results.length; ++j)
if(results[j] == random_int)
random_int = (int)((Math.random() * results.length) + min);
j = -1;
continue;
if(j == results.length - 1)
results = random_int;
continue outer_loop;
return results;
} // generate unique random numbers
public static void main( String args[])
Frame GridLayFrame = new Frame ( " Grid Layout Frame ");
GridLayEx2 gl = new GridLayEx2();
gl.init();
GridLayFrame.add(gl);
GridLayFrame.pack();
GridLayFrame.setSize(GridLayFrame.getPreferredSize());
GridLayFrame.show();
GridLayFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
} // end of main method

hi,
i got one doubt in the previous application. i want to put labels in the circle manner while changing my label positions. Now it is rectangular type. And also i want to change my background color of JFrame. Please see my code ...
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.GregorianCalendar;
public class GridLayEx6 extends JApplet{ 
   private Random r = new Random(); 
   private ActionListener taskPerformer;
   private javax.swing.Timer timer;  
   private GridLayout glt;  
   private JLabel[] myLabel;     
   GregorianCalendar todayDate = new GregorianCalendar();     
   long fromTime,toTime,elapsedTime;
   public void init() {     
        glt = new GridLayout(3,3);     
      Font boldFont = new Font("Helvetica", Font.BOLD, 25);     
      Font plainDerived = boldFont.deriveFont(Font.PLAIN, 25);     
         myLabel = new JLabel[9];     
         String myUrl = "C:\\Regoti\\Vision\\AP\\Project\\Version1\\images\\MyArrow.jpg";
         String myUrlA = "C:\\Regoti\\Vision\\AP\\Project\\Version1\\images\\MyA.jpg";     
         URL url = null;     
   try{
   myLabel[0] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);     
   myLabel[1] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
   myLabel[2] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
   myLabel[3] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
   myLabel[4] = new JLabel("+", SwingConstants.CENTER);     
   myLabel[5] = new JLabel(new ImageIcon(myUrlA), SwingConstants.CENTER);
   myLabel[6] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
   myLabel[7] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
   myLabel[8] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
   myLabel[2].setVerticalAlignment(SwingConstants.NORTH);     
   myLabel[4].setFont(boldFont);     
   getContentPane().setLayout(glt);     
  } catch( Exception e)
    { System.out.println(" Exception occurs "+e);}
   int delay = 20000; //milliseconds     
   ActionListener taskPerformer = new ActionListener() {     
   public void actionPerformed(ActionEvent evt) {      
             randomDuke();
   timer = new javax.swing.Timer(delay, taskPerformer);     
   addKeyListener(new KeyAdapter()      {        
      public void keyPressed(KeyEvent e){           
             GridLayEx6 gl2 = (GridLayEx6)e.getSource();           
                 switch(e.getKeyCode())
                       case(KeyEvent.VK_ENTER): 
                            gl2.randomDuke();                 
                            break;
                   case(KeyEvent.VK_SPACE):              
                        if(gl2.timer.isRunning())                    
                          { gl2.timer.stop();                 
                                toTime = System.currentTimeMillis();
                             elapsedTime = toTime - fromTime;
                             System.out.println("toTime : "+toTime);
                             System.out.println("elapsedTime : "+elapsedTime);
                              gl2.timer.start();
                               gl2.randomDuke();
                           break;
                   case(KeyEvent.VK_KP_RIGHT):case(KeyEvent.VK_KP_UP):              
                   case(KeyEvent.VK_RIGHT):case(KeyEvent.VK_UP):              
                     int delay = gl2.timer.getDelay();
                     if(delay > 0)                    
                        gl2.timer.setDelay(delay - 100);                 
                        break;
                   case(KeyEvent.VK_KP_LEFT):case(KeyEvent.VK_KP_DOWN):              
                   case(KeyEvent.VK_LEFT):case(KeyEvent.VK_DOWN):
                        int delay = gl2.timer.getDelay();                  
                        if(delay < 10000)                    
                             gl2.timer.setDelay(delay + 100);                  
                             break;
                   //timer.start();  
         } // end of init method  
         public void start()   {     
              timer.start();     
                while(!isFocusOwner())        
                        requestFocus(); 
         } // end of start method     
         public void stop(){    
              timer.stop();
        } // end of stop method     
         /** To make sure we have focus in application *  
         * mode if JFrame loses focus control          *  
         * - non standard usage of paintComponent      */    
         public void paintComponent(Graphics g)   {
              while(!isFocusOwner())        
                   requestFocus();  
        public void randomDuke()   {     
              fromTime = System.currentTimeMillis();
              System.out.println("fromtime : "+fromTime);     
              getContentPane().removeAll();     
              int[] values = new int[9];     
              int temp;
              values = gen_pos_uni_ran_num(0,8);     
              for ( int i=0; i<=8;i++)
                      if ( values[i] == 4)
                             temp = 4;
                             values[i] = values[4];
                             values[4] = temp;
              for(int q = 0; q < 9; q++)   
                    getContentPane().add(myLabel[values[q]]);    
                   myLabel[0].revalidate();
                   myLabel[1].revalidate();
                   myLabel[2].revalidate();
                   myLabel[3].revalidate();
                   myLabel[5].revalidate();
                   myLabel[6].revalidate();
                   myLabel[7].revalidate();
                   myLabel[8].revalidate();
                } // end of randomDuke method  
          public int[] gen_pos_uni_ran_num(int min, int max)   {     
              int results[] = new int[Math.abs(max - min) + 1];     
              for(int q = 0; q < results.length; ++q) 
                   results[q] = -1;     
              outer_loop:     
              for(int q = 0; q < results.length; ++q)  
                   int random_int = (int)((Math.random() * results.length) + min);        
                for(int j = 0; j < results.length; ++j)       
                    if(results[j] == random_int)            {              
                        random_int = (int)((Math.random() * results.length) + min);              
                        j = -1;
                  continue;           
                 if(j == results.length - 1)
                      results[q] = random_int;              
                      continue outer_loop;
              return results;  
              } // generate unique random numbers  
              public static void main( String args[])
                    JFrame GridLayFrame = new JFrame ( " Grid Layout Frame ");     
                   GridLayFrame.setSize(500,500);     
                   GridLayEx6 gl = new GridLayEx6();     
                   gl.init();     
                   GridLayFrame.getContentPane().add(gl);     
                   //GridLayFrame.setBackgroundColor(Color.white);
                   GridLayFrame.setVisible(true);
                   gl.start();     
                   GridLayFrame.addWindowListener(new WindowAdapter()      
                     public void windowClosing(WindowEvent e)         
                    System.exit(0);         }      });  
              } // end of main method
              }

Similar Messages

  • Thread problem in swings

    I have made an application in swings i have stored the class files in a system and call that class files by a batfile shortcut in two diff. pcs .and i am tring to get an value of a Jtextarea in an event When I tried to run this application at the same time from 2 diff PCS,with diff string input in text area It is giving me the same vlaue.
    Tell me Y it is so.and how can i rectify it
    javauser

    Very strange... what makes you think that this is a threading problem?

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

  • Problem with threads in my swing application

    Hi,
    I have some problem in running my swing app. Thre problem is related to threads.
    What i am developing, is a gui framework where i can add different pluggable components to the framework.
    The framework is working fine, but when i press the close action then the gui should close down the present component which is active. The close action is of the framework and the component has the responsibility of checking if it's work is saved or not and hence to throw a message for saving the work, therefore, what i have done is that i call the close method for the component in a separate thread and from my main thread i call the join method for the component's thread.But after join the whole gui hangs.
    I think after the join method even the GUI thread , which is started for every gui, also waits for the component's thread to finish but the component thread can't finish because the gui thread is also waiting for the component to finish. This creates a deadlock situation.
    I dont know wht's happening it's purely my guess.
    One more thing. Why i am calling the component through a different thread, is because , if the component's work is not saved by the user then it must throw a message to save the work. If i continue this message throwing in my main thread only then the main thread doesnt wait for user press of the yes no or cancel button for saving the work . It immediately progresses to the next statement.
    Can anybody help me get out of this?
    Regards,
    amazing_java

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Thread problems in Swing

    I'm building I guess its like an online strategy game. On the map, when you move your mouse to within 50 of the bounds of the applet, it'll start scrolling the map at a predetermined speed.
    When working with applets/painting/threads this worked like a dream. Java was too fast for itself and I had to even slow the scrolling down.
    Now, I'm building the whole thing in swing instead. The map is technically a JLabel inside of a Container that gets loaded into the main contentPane.
    The only way I could use setLocation in my threads run method was to setLocation on the Container, not the JLabel. Odd fix to that problem. (I kept getting a null pointed exception otherwise)
    My problem is, when the mouse is in that 50 pixels, the program knows it, but it just /lags/. Horribly. I set a counter to print to the console and when the mouse enters the area it moves to like 15 (in 0.001 seconds), and stops. I move my mouse around, and a few seconds later I see 700-705, then it stops, and jumps ahead again if I move my mouse.
    So my program will now scroll the map in very small, /very/ jagged bits.
    It's not an intensive program or code. I don't see how or why the thread can't continually run it.
    My run method:
    public void run() {
              while (true) {
                   if (mouseX > 650 && mouseX <= 700)
                        moveRight = true;
                            if (moveRight == true) {
                        if (mapCurrentX + screenX < (xDimension)) {
                             mapCurrentX -= moveSpeed;
                             contentPane.setLocation(mapCurrentX, mapCurrentY);
                   try {
                        // Stop thread for 20 milliseconds
                        Thread.sleep(20);
                   catch (InterruptedException ex) {
                        // do nothing
                   Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
         }

    I got this when I ran it ^_^;; Gonna try to fix it
    Wrong Thread
    java.lang.Exception: Stack trace
         at java.lang.Thread.dumpStack(Unknown Source)
         at ThreadCheckingRepaintManager.checkThread(ThreadCheckingRepaintManager.java:13)
         at ThreadCheckingRepaintManager.addInvalidComponent(ThreadCheckingRepaintManager.java:6)
         at map.<init>(map.java:74)
         at ClientMain3.init(ClientMain3.java:12)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)

  • Display Problem in Swing application

    I have a java application.I am running it in Windows XP sp2.In this i see that some of the icons are missing and also not properly displayed.Can anybody tell me what is the reason behind this.

    I think you can go ahead and ignore that RA by talking to Edmond Denis

  • Java Swing application problem in Windows vista

    When we execute the Swing application in windows vista environment.
    The look and feel of the swing components are displayed improperly.
    Do we need to put any specific look and feel for windows vista environment or any specific hardware configuration is required to setup windows vista environment.
    Please give some inputs to solve the problem.
    We have tried with the following sample code to run in windows vista.
    * Vista.java
    * Created on December 5, 2006, 5:39 PM
    public class Vista extends javax.swing.JFrame {
    /** Creates new form Vista */
    public Vista() {
    initComponents();
    pack();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
    jButton1 = new javax.swing.JButton();
    jToggleButton1 = new javax.swing.JToggleButton();
    jPanel1 = new javax.swing.JPanel();
    jCheckBox1 = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    getContentPane().setLayout(null);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jButton1.setText("Button 1");
    getContentPane().add(jButton1);
    jButton1.setBounds(20, 20, 170, 30);
    jToggleButton1.setText("Togle btn");
    getContentPane().add(jToggleButton1);
    jToggleButton1.setBounds(100, 80, 90, 20);
    jPanel1.setLayout(null);
    jCheckBox1.setText("jCheckBox1");
    jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
    jPanel1.add(jCheckBox1);
    jCheckBox1.setBounds(10, 40, 130, 13);
    getContentPane().add(jPanel1);
    jPanel1.setBounds(10, 150, 200, 130);
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(210, 150, 164, 94);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1);
    jTextField1.setBounds(240, 30, 140, 30);
    pack();
    }// </editor-fold>//GEN-END:initComponents
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Vista().setVisible(true);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
    }

    When we execute the Swing application in windows
    vista environment.
    The look and feel of the swing components are
    displayed improperly.Improperly means what? You must be aware that Vista's native L&F certainly isn't supported yet.

  • Problem with "find" mode in adf/swing application

    Hi all,
    I'm working on ADF Swing application which uses MS SQL Server 2005 (JDeveloper 10g 10.1.3)
    I think that my issue might be well-known…sorry if it has been already discussed somewhere else…
    I have a problem with the “find” mode for a detail panel in a master-detail form…(To make it clear the “find” mode is switched on when clicking on the special button on a navigation panel).
    So this mode works well in a master panel, but it demonstrates strange behavior on a detail panel, i.e. it takes me two attempts to find the necessary child object and it doesn’t switch back in a simple way from this mode to the normal mode….say if we are in the department 10 (Dept is a master form) we can’t simply find KING employee (Emp is a detail form)…is there any workaround for this?
    Thanks in advance. Alex.

    Hi Frank, please look this issue

  • Problem in Opening HTML Page in Internet Explorer from my Swing Application

    Hi,
    I am opening a HTML file in Internet Explorer from my swing application.I am using the code given below
    private final static String WIN_FLAG = "url.dll,FileProtocolHandler";
    private final static String WIN_PATH = "rundll32";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    // url is HTML file Path
    Process p = Runtime.getRuntime().exec( cmd );
    Here there are two things i need to address ...
    1)The HTML file is opening up,but it always opens behind the swing application,that makes me every time to maximize the HTML file after it being opened up.I want to open it in front of the Swing Application.I need to implement "Always On Top" functionality for the html page.
    2)Whenever i trigger action to open different HTML page,it opens in new Internet Explorer window.
    I need to open it in same IE window.
    how to solve out these problems ??? any help would be greatly appreciated .Thanks in advance.
    - Manikandan

    any idea about this ????

  • UI problem when run java swing application on MAC OSX

    Hello,
    I have problem when i run my java swing application on MAC OSX.
    Dialog box is not properly visible in MAC means ita size increses.
    its size incresed and and some content or buttons on that dialog are not fully visible.
    I can only see partial message or button.
    If any one have idea about this problem then give the solution.
    Thanks :)
    Shweta

    I am using following way to create dialog
    JOptionPane optionpane = new JOptionPane(new Object[]{lblMsgUp}, JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, choices, "Save");
    JDialog dialog = optionpane.createDialog(parent, "Save");
    dialog.setSize(450, 125);
    dialog.setVisible(true);

  • Problem while creating JAR file for my swing application

    Hi...
    Using my swings application I am trying to Run different software�s .
    My program is Running fine from command prompt. If I create JAR file
    It is giving error like �Failed to load Main-Class manifest attribute from .jar�
    Can anybody help me to creating JAR file
    Thanks in advance
    Cheers
    Mallik

    hi,
    User following command
    jar-cmf textfile_name.txt Jarfile_name *
    here you have to make manifest file
    and making jar file you have reach there by command promt
    and manifest file have some constraint also as well as format
    format are
    Manifest-Version: 1.0
    Class-path: jar file name which are using in app separed by space
    Created-By: 1.5.0 (Sun Microsystems Inc.)
    Main-Class: Main class name
    and end of file is not have carriage return

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

  • Problems After shifting swing application from jdk1.3 to 1.4

    hi,
    i have shifted my Swing application from jdk1.3 to 1.4, some component settings changed in j2se1.4. are listed below
    1). i have added JComboBox to JPanel using BoxLayout, in jdk1.3 it is normal where as in 1.4 comboBox height is increased to panel height.
    Sample code
    (in a Panel)
         setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    add(getYearComboBox());
         add(getMonthNameComboBox());
         add(getDayOfMonthComboBox());
    2). in jdk1.3 the icon which is set to JFrame is visible in the JOptioPane.showConfirmationDialog() also, but in 1.4 the icon is not visible in conformation dialog box.
    Sample Code
    in a JFrame's constructor
    public OptionPaneTest()
    ImageIcon icon = new ImageIcon("icon.gif");
    setIconImage(icon.getImage());     
    setSize(250,100);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
    setVisible(true);
    JOptionPane.showMessageDialog(this,"hai", "Hai",JOptionPane.WARNING_MESSAGE);
    3). the Labels added to the panel or frame are displaying in light blue color with jdk1.3 and the same label displaying in black with j2se1.3
    Sample Code
    in a JPanel
    setLayout(new BorderLayout(20, 20));
    add(new JLabel("Testing Label Color"), BorderLayout.CENTER);
    please send solution to any or all.
    thanks in advance,
    Pavan.DV

    Thanks for your sugession.
    You realized me by showing the fact that there are no many classes
    Keep suggesting like this.
    I don't even know how to see the API documentation Before you told me.
    Don't take any issue as simple thing and never give foolish suggessions like this.
    If you know the Answer then share it or else musukoni kurcho ra

  • Can not launch swing application from Java Web Start 1.6.0_37

    I have a dynamic generated jnlp file from a serlvet. When I used Java Web Start to start the swing application, it failed. The exception showed
    com.sun.deploy.net.FailedDownloadException: Unable to load resource: http://xxxx.xx.com:9080/dilpipweb/Test-1.0-SNAPSHOT.jar
         at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source)
         at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
         at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
         at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
         at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
         at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
         at com.sun.javaws.LaunchDownload$DownloadTask.call(Unknown Source)
         at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
         at java.util.concurrent.FutureTask.run(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    I used janela to validate the generated jnlp file. It was valid. I also checked the tomcat access log, it showed that the Test-1.0-SNAPSHOT.jar file was accessed correctly (with a 200 return code).
    Can anyone help me what was the problem?
    Thanks,

    Hi.
    I got a different problem. My Corba application works in JRE 1.6, but doesn't works in JRE 1.5.X. I got an unexpected error and my console shows:
    getSubjectX500Principal NoSuchMethodError: java.lang NoSuchMethodError
    #### Java Web Start Error:
    #### null
    Can you help me?

  • Multithreading in a Swing Application

    Hello,
    my Problem is:
    I did a Swing Application which shows data records from a Database.
    In a layer I fetch the data records from the database and create "SelectRowObjects" which are put into a Vector These SelectRowObjects have a Method "createView()" which returns a JPanel
    In My Application I click on the button "fetch data" and then the EventDispatchingThread executes the DataBaseConnection ....... until The Panels are shown in my Application.
    That takes a several time.
    Can I create an extra Thread??
    How can I do so??
    Can you give me a short hint???
    Thank you

    Have a look here, particularly post #4 from camickr, and follow his link
    http://forum.java.sun.com/thread.jsp?forum=54&thread=505438&tstart=0&trange=50

Maybe you are looking for