Results 1 to 12 of 12
Like Tree1Likes
  • 1 Post By maaaaarco

Thread: Jframe form issue, calling a method from another class

  1. #1
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Default Jframe form issue, calling a method from another class

    Hi guys... i have a little problem with a Swing application...

    i have a Jframe form named mainFrame, with some text fields etc... when i run my applications this is the first form that will appear...

    now when i have setted all the fields, i press the Execute Jbutton, the actionPerformed associated to this button calls my function named Execute...

    Now the function Execute take all the values of the text fields and put them in some String variables. After that create an instance of a class named executeClass, located in a different package, and call his method doSomething, passing all the String variables....

    doSomthing method, as the name says, do something with that String variables and then should create a new Jframe form called resultFrame, located in the same package of mainFrame

    During all this mainFrame will be never disposed, will be always visible...

    The point is this...
    if i call the doSomething method from a simple class, everything is ok....
    if i call doSomething method from mainFrame, after some seconds an empty form will appear and the application will be blocked, and i will have to terminate it by NetBeans.

    Now i'm not expert with Swing... and i know that there are some issue with thread and Swing...

    Did any of you have just an idea of what could be the error ?

    The application code is very long... to simplify i put just an example...

    Java Code:
    //mainForm
    package x;
    import y.executeClass;
    
    public class mainFrame extends Jframe {
       ...
       execute() {
          new executeClass().doSomething(String ......);
       }
    }
    
    //resultFrame
    package x;
    
    public class resultFrame extends Jframe {
       public resultFrame(String result) {
          ...
          setvisible(true);
       }
    }
    
    //executeClass
    package y;
    import x.resultFrame;
    
    public class executeClass {
       ...
       public doSomething(String ....) {
          ...
          new resultFrame("this is the result....");
       }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Jframe form issue, calling a method from another class

    I believe that it is impossible for us to know with certainty what is wrong based on the code you've presented, and this means that you'll need to present more information. Having said that, please understand that we don't want to see your entire program but rather the smallest program possible that has compilable and runnable code and that demonstrates your problem. Again to reiterate, we don't want to see your whole program, especially if it's larger than 60 lines long, but rather you should condense your code into the smallest bit that still compiles and runs, has no extra code that's not relevant to your problem, has no local images or other local requirements (i.e., database) but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:

    SSCCE

    Again, if the code is compilable and runnable more people will be able to help you.

    Best of luck!

  3. #3
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Default Re: Jframe form issue, calling a method from another class

    ok guys... as soon as possible i'll post a little part of the program ;)

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Jframe form issue, calling a method from another class

    Quote Originally Posted by maaaaarco View Post
    ok guys... as soon as possible i'll post a little part of the program ;)
    OK good, but remember if you want the best chances of quick and useful help, try to make sure that the code you post is both compilable and runnable, but again contains no extra code that is unrelated to your problem. Yes, this will take quite a bit of effort on your part, but it is often well worth it.

  5. #5
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Talking Re: Jframe form issue, calling a method from another class

    Ok... this code will cause the same effect...


    MAINFORM:
    Java Code:
    package javaapplication1;
    
    public class MainJFrame extends javax.swing.JFrame {
         
        private javax.swing.JButton jButton1;
    
        public MainJFrame() {
            initComponents();
            setVisible(true);
        }
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            new ExecuteClass().doSomething();
        }
    
        public static void main(String args[]) {
            new MainJFrame();
        }
    
    //YOU COULD IGNORE THIS PART - NETBEANS HAS GENERATED IT, IS JUST TO BUILD THE FORM AND ADD THE COMPONENTS 
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jButton1 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jButton1.setText("click me !");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(137, 137, 137)
                    .addComponent(jButton1)
                    .addContainerGap(165, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(134, 134, 134)
                    .addComponent(jButton1)
                    .addContainerGap(141, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    //EXECUTECLASS
    Java Code:
    package javaapplication1;
    
    public class ExecuteClass {
        
        public void doSomething() {
            boolean res = WarningJFrame.warningMessage();
            
            System.out.println(res);
        }   
    }
    //WARNINGFRAME
    Java Code:
    package javaapplication1;
    
    
    public class WarningJFrame extends javax.swing.JFrame {
    
        private boolean res;
    
        private javax.swing.JButton buttonFalse;
        private javax.swing.JButton buttonTrue;
        
        public WarningJFrame() {
            initComponents();
            setVisible(true);
        }
        
        public static boolean warningMessage() {
            WarningJFrame w=new WarningJFrame();
            
            try {
                synchronized(w) {
                    w.wait();
                }
            } catch (InterruptedException e) {
                w.res = false;
            } finally {
                w.dispose();
            }
            return w.res;
        }
    
        private void buttonTrueActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            res=true;
            setVisible(false);
            synchronized(this) {
                this.notify();
            }
        }
    
        private void buttonFalseActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            res = false;
            setVisible(false);
            synchronized(this) {
                this.notify();
            }
        }
    
    //AGAIN, YOU COULD IGNORE THIS PART
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            buttonTrue = new javax.swing.JButton();
            buttonFalse = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            buttonTrue.setText("true");
            buttonTrue.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonTrueActionPerformed(evt);
                }
            });
    
            buttonFalse.setText("false");
            buttonFalse.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buttonFalseActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(57, 57, 57)
                    .addComponent(buttonTrue)
                    .addGap(60, 60, 60)
                    .addComponent(buttonFalse)
                    .addContainerGap(150, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(125, 125, 125)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(buttonTrue)
                        .addComponent(buttonFalse))
                    .addContainerGap(150, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    You will see that, after you press the only one button in the mainFrame the application will be blocked

    I will explain what should do this code:

    The main form will display to you a button named "click me!". When you click the button, a new instance of executeClass will be created, and the method doSomthing will be called.

    The method doSomething will call the static method warningMessage, that should return a boolean value.

    the warningMessage method create a new instance of WarningJframe, wait until it terminates, and return the value to doSomething
    Last edited by maaaaarco; 09-23-2012 at 07:41 PM.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Jframe form issue, calling a method from another class

    You're calling wait on the Swing event thread:

    Java Code:
       public static boolean warningMessage() {
          WarningJFrame w = new WarningJFrame();
    
          try {
             synchronized (w) {
                w.wait();
             }
          }
    Since this thread is responsible for all Swing graphics and user interactions, if you call wait on it, it should come as no surprise that you will have effectively frozen the entire GUI rendering it useless. Why not instead use a modal dialog such as a JDialog or a JOptionPane since this is precisely what they are built for?

    Also, next time you create an SSCCE, please leave out all the NetBeans formatting junk. You are creating the most simple of GUI's with one or two components at most, and for this you don't need to clutter your SSCCE with needless code completely unrelated to your problem. Use some very simple layouts, say FlowLayout (the default for JPanel), and save us the pain of having to go through too much code again that's not related to your problem.

    For instance, contrast the size of the code you've posted with this program:

    Java Code:
    import java.awt.event.ActionEvent;
    
    import javax.swing.*;
    
    public class MainJFrame2 {
    
       private static void createAndShowGui() {
          final JPanel mainPanel = new JPanel();
          mainPanel.add(new JButton(new AbstractAction("Click Me") {
    
             @Override
             public void actionPerformed(ActionEvent arg0) {
                String[] options = {"True", "False"};
                int result = JOptionPane.showOptionDialog(mainPanel, "Please make a choice",
                      "True or False?", JOptionPane.DEFAULT_OPTION,
                      JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                if (result >= 0) {
                   System.out.println("You selected: " + options[result]);
                }
             }
          }));
    
          JFrame frame = new JFrame("MainJFrame2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    Last edited by Fubarable; 09-23-2012 at 10:18 PM.

  7. #7
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Default Re: Jframe form issue, calling a method from another class

    Quote Originally Posted by Fubarable View Post
    You're calling wait on the Swing event thread:

    Why not instead use a modal dialog such as a JDialog or a JOptionPane since this is precisely what they are built for?
    Because i didn't know them ! :D

    Thx for helping me ! Now i have solved my problem ;)

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Jframe form issue, calling a method from another class

    You're welcome!

  9. #9
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Default Re: Jframe form issue, calling a method from another class

    Sorry man... i need your help again... i get another similar "error"

    As always i have the main frame with a button, when you press the button a new instance of ExecClass will be created and doSomething method will be called.
    doSomething method will create a new instance of ProgressBarClass, to show a Jframe with a JprogressBar in it. After that doSomething method should update the value of JprogressBar, but here comes the problem.

    After creating the JprogressBar the GUI will be frozen like before, but as you will seen from the standard output the application still go on. Could you help agai ?
    Thx !

    Java Code:
    //MAINFORM
    package javaapplication2;
    
    public class MainFrame {
        
        public static void main(String[] args) {
            
            JFrame frame = new JFrame();
            JButton button = new JButton("click me");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new ExecClass().doSomething();
                }
            });
            
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(button);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
        
    }
    
    //EXECCLASS
    package javaapplication2;
    
    public class ExecClass {
        
        public void doSomething() {
            int n = 0;
            ProgressBarClass p = new ProgressBarClass(0, 10);
            
            while(n<10) { 
                try { 
                    Thread.sleep(1000); 
                    p.increment(++n);
                    System.out.println(n);
                } catch (InterruptedException e) {}
            }
            
            System.out.println("Finish!");
            p.close();
        }   
    }
    
    //PROGRESSBARCLASS
    package javaapplication2;
    
    public class ProgressBarClass {
        
        private JProgressBar progBar;
        private JFrame frame;
        
        public ProgressBarClass(int min, int max) {
            progBar = new JProgressBar(min, max);
            progBar.setStringPainted(true);
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(progBar);
            frame.setLocationByPlatform(true);
            frame.pack();
            frame.setVisible(true);
        }
        
        public void increment(int x) {
            progBar.setValue(x);
        }
        
        public void close() {
            frame.dispose();
        }
        
    }
    Last edited by maaaaarco; 09-24-2012 at 07:55 PM.

  10. #10
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Default Re: Jframe form issue, calling a method from another class


  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Jframe form issue, calling a method from another class

    Yes, it's the same issue -- tying up the Swing event dispatch thread or EDT with a long-running or waiting process, here Thread.sleep(...). Be sure to read the article on Concurrency in Swing for more on this.

  12. #12
    maaaaarco is offline Member
    Join Date
    Nov 2011
    Posts
    9
    Rep Power
    0

    Default Re: Jframe form issue, calling a method from another class

    Thanks again! The article that you posted was very very useful to me ! Now my application runs as it was supposed to do ;)
    Fubarable likes this.

Similar Threads

  1. Replies: 8
    Last Post: 04-18-2012, 04:58 PM
  2. JFrame Form being seen as java class...
    By TWIC in forum NetBeans
    Replies: 0
    Last Post: 08-28-2011, 11:10 AM
  3. Child-Class Calling a Method in a Parent-Class
    By Blah_ in forum New To Java
    Replies: 5
    Last Post: 09-29-2009, 02:48 AM
  4. Replies: 29
    Last Post: 09-25-2008, 07:55 PM
  5. Calling a method on original class from created class
    By kpedersen in forum Advanced Java
    Replies: 4
    Last Post: 08-20-2008, 12:25 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •