2

I never understood SwingUtilities.invokeLater,that is the reason i kept avoiding it until now.But its very important to make Swing Thread safe. Well please excuse me, as this is my first time with this. I am trying to Close the window after some data base query.So,as far as i understood, any updation in UI must be handled by SwingUtilities.invokeLater.Here is my work:

Main:

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new forminsert().setVisible(true);
forminsert f=new forminsert();
    }
    });

    }
  public forminsert() {
    initComponents();
}

public class forminsert extends javax.swing.JFrame {    
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setUndecorated(true);

    jPanel1.setBackground(new java.awt.Color(0, 0, 0));
    jPanel1.setBorder(javax.swing.BorderFactory.createMatteBorder(3, 3, 3, 3, new java.awt.Color(0, 204, 204)));
              /////***REST CODE***/////           

}

listner on ADD button

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)               {                                         
 new Thread(new thread1()).start();

}                                        
public class thread1 implements Runnable
{

    public void run() {
     insert ins=new insert();
    ////code for inserting///     
    }
 }

listner on browse button

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                {                                         
    JFileChooser ss=new JFileChooser();
    ////Code to choose the file////
                 }                                        

here is the problem,code to exit.

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

forminsert f=new forminsert();f.call();
}

public  void call()
{
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
 jPanel1.setVisible(false);
getRootPane().setVisible(false);

    }
    });

Screen: screen short

Please explain me where i am going wrong,i dont want to use System.exit and excuse me for asking too many questions.Thanks.

UPDATE:

Here is a sample working code as requested by @trashgod

package faltur;

import java.io.File;
import javax.swing.JFileChooser;

public class insert extends javax.swing.JFrame {

/** Creates new form insert */
public insert() {
    initComponents();
}


@SuppressWarnings("unchecked")

 private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setUndecorated(true);

    jPanel1.setForeground(new java.awt.Color(240, 240, 240));

    jButton1.setText("Browse..");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("exit");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton1)
                    .addGap(31, 31, 31)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(153, 153, 153)
                    .addComponent(jButton2)))
            .addContainerGap(99, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(66, 66, 66)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(87, 87, 87)
            .addComponent(jButton2)
            .addContainerGap(94, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,   javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                {                                         
 JFileChooser ss=new JFileChooser();
 ss.showOpenDialog(jTextField1);

 File f=ss.getSelectedFile();

   path=f.toString();
    System.out.println(path);

}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
  insert in=new insert();
  in.exit();/////////////CALLS exit()/////////////////modify this//////
}


public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new insert().setVisible(true);
        }
    });
}
public void exit()////////////////////////MODIFY THIS///////////////////
{
jPanel1.getRootPane().setVisible(false);

}

private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;

 public String path="";
}

Please run and tell how to modify exit() so that it closes the window.Thanks once again.

joey rohan
  • 3,505
  • 5
  • 33
  • 70
  • For starters, why **don't you** use `SwingUtilities.invokeLater` there? – Marko Topolnik Dec 19 '12 at 11:17
  • @MarkoTopolnik where exactly? – joey rohan Dec 19 '12 at 11:19
  • At the point you use `invokeLater`. – Marko Topolnik Dec 19 '12 at 11:19
  • 2
    Please start Classnames with a Capital. And why do you create new instances of `forminsert` all the time? – Fildor Dec 19 '12 at 11:19
  • 1
    You can understand Swing and threads better after reading this: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html – fredcrs Dec 19 '12 at 11:21
  • @MarkoTopolnik i am using `SwingUtilities.invokeLater`inside Main also – joey rohan Dec 19 '12 at 11:23
  • You clearly aren't. In fact, the class `SwingUtilities` is not referenced anywhere in your code. – Marko Topolnik Dec 19 '12 at 11:24
  • 1
    @MarkoTopolnik: As of 1.3 this method is just a cover for `java.awt.EventQueue.invokeLater()`. – trashgod Dec 19 '12 at 11:25
  • 2
    @trashgod That should be left to the implementation. Code should be written against `SwingUtilities.invokeLater`. – Marko Topolnik Dec 19 '12 at 11:26
  • @MarkoTopolnik same method on EventQueue _is_ referenced – kleopatra Dec 19 '12 at 11:26
  • @MarkoTopolnik wont `java.awt.EventQueue.invokeLater` will do more or less the same thing? – joey rohan Dec 19 '12 at 11:27
  • 2
    invokeLater is not the major malfunction here ... – Fildor Dec 19 '12 at 11:27
  • It **may** do the same and it definitely does the same on certain implementations. However, it is not idiomatic to write your code against that method directly. It's even more confusing that you consistently refer to `SwingUtilties` in your question, but not in your code. – Marko Topolnik Dec 19 '12 at 11:27
  • darn, @trashgod beat me by a full half-minute :-) Curious, why would you (@Marko) would prefer SwingUtilities? Don't see any reason to not follow the doc. – kleopatra Dec 19 '12 at 11:29
  • @trashgod last time i used component hidden to close the window,more or less the same. – joey rohan Dec 19 '12 at 11:30
  • In the shown code you also copied the Constructor of `forminsert` to a wrong place, I guess ... I really think the main problem is the creation of new instances of the form rather than the correct version of invokelater. – Fildor Dec 19 '12 at 11:30
  • 1
    @MarkoTopolnik: I agree that using both `EventQueue` and `SwingUtilities` in same the question is confusing. I'd encourage consistency, modulo [Emerson](http://en.wikipedia.org/wiki/Self-Reliance). :-) – trashgod Dec 19 '12 at 11:47
  • @trashgod In fairness, Emerson had something else in mind, but still, I appreciate the reference :) Even though, after re-reading the javadoc for `SwingUtilities.invokeLater`, I can agree that it is a documented fact that these are the same, the fact remains that the question confuses gratuitously. – Marko Topolnik Dec 19 '12 at 11:52
  • +1 for [sscce](http://sscce.org/). – trashgod Dec 19 '12 at 16:10

2 Answers2

6

Because your frame's default close operation is EXIT_ON_CLOSE, you can send WindowEvent.WINDOW_CLOSING via dispatchEvent(), as shown here. Given a JFrame f,

private static final String EXIT = "Exit";
private Action exit = new AbstractAction(EXIT) {

        @Override
        public void actionPerformed(ActionEvent e) {
            f.dispatchEvent(new WindowEvent(
                f, WindowEvent.WINDOW_CLOSING));
        }
    };
private JButton b = new JButton(exit);

See also How to Use Actions and follow common coding conventions.

Addendum: Based on the revised code, here is one approach to exiting the program. Note class names typically start with a capital letter, while instance names are lower case.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    insert.dispatchEvent(new WindowEvent(
        insert, WindowEvent.WINDOW_CLOSING));
}

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            insert = new Insert();
            insert.setVisible(true);
        }
    });
}

private static Insert insert;
...
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • why getRootPane().setVisible(false) it not working in my code? – joey rohan Dec 19 '12 at 11:36
  • I don't see that you need `getRootPane()`, except maybe to call `setDefaultButton()`; and you don't need `invokeLater()`, of any provenance, in the `Action`. If you still have problems, please edit your question to include an [sscce](http://sscce.org/). – trashgod Dec 19 '12 at 11:40
3

Well insted of using foo.setVisible(false), simply i changed it to setVisible(false), and it worked.

joey rohan
  • 3,505
  • 5
  • 33
  • 70