Results 1 to 2 of 2
  1. #1
    dataphile's Avatar
    dataphile is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Question Prompt for value in swing thread

    Hi

    I need to control the gui from the application logic. So here is a simple example of what I need to do:

    It starts a main thread, prompts for a value using a swing gui, while the main thread is waiting. The main thread needs to resume when the button is clicked.

    I get an IllegalMonitorStateException when the gui thread tries to tell the main thread to resume because it is not the owner.

    Thanks in advance.

    Java Code:
    package example.gui;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class TextInput implements Runnable {
        LockMechanism lm = new LockMechanism();
        String value = "";
        private final String prompt;
    
        /**
         * Get a value from a swing gui
         * 
         * @param args
         * @throws InterruptedException
         */
        public static void main(String[] args) throws InterruptedException {
            String v = TextInput.getInput("Enter a number");
            System.out.println("You entered " + v);
        }
    
        /**
         * Start a swing gui in a new thread to prompt from a value
         *
         * @param prompt
         * @return
         */
        public static String getInput(String prompt) {
            TextInput ti = new TextInput(prompt);
            try {
                Thread t = new Thread(ti, "gui");
    //            t.join();
                try {
     [COLOR="SeaGreen"]               ti.lm.getProcLock().lock();
                    t.start();
                    ti.lm.lock();[/COLOR]
                } catch (InterruptedException ie) {
                } finally {
                    ti.lm.getProcLock().unlock();
                }
            } catch (Exception ex) {
                System.err.println("Exception");
            }
            return ti.value;
        }
    
        /**
         * Constructor
         * 
         * @param prompt
         */
        public TextInput(String prompt) {
            this.lm = new LockMechanism();
            this.prompt = prompt;
        }
    
        /**
         *
         */
        public void run() {
            JLabel label = new JLabel(prompt, JLabel.LEFT);
            final JFrame frame = new JFrame();
            final JTextField jTextField = new JTextField(10);
            JButton button = new JButton("Submit");
    
            button.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    //get the value from the textfield
                    value = jTextField.getText();
                    //resume main thread
    [COLOR="Red"]                lm.unLock();[/COLOR]
                    //close the gui
                    frame.dispose();
                }
            });
    
            Box box = new Box(BoxLayout.Y_AXIS);
            box.add(label);
            box.add(jTextField);
            box.add(button);
    
            frame.getContentPane().add(box);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    
        class LockMechanism {
    
            private Lock procLock = null;
            private Condition processing = null;
            private boolean canProcess;
    
            public LockMechanism() {
                this.procLock = new ReentrantLock();
                this.processing = procLock.newCondition();
                this.canProcess = false;
            }
    
            public void lock() throws InterruptedException {
                while (!canProcess) {
                    processing.await();
                }
            }
    
            public void unLock() {
                canProcess = true;
                try {
                    processing.signalAll();
                } catch (IllegalMonitorStateException imse) {
                    System.err.println("IllegalMonitorStateException");
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
            }
    
            public boolean isCanProcess() {
                return canProcess;
            }
    
            public void setCanProcess(boolean canProcess) {
                this.canProcess = canProcess;
            }
    
            public Lock getProcLock() {
                return procLock;
            }
    
            public void setProcLock(Lock procLock) {
                this.procLock = procLock;
            }
    
            public Condition getProcessing() {
                return processing;
            }
    
            public void setProcessing(Condition processing) {
                this.processing = processing;
            }
        }
    }

  2. #2
    dataphile's Avatar
    dataphile is offline Member
    Join Date
    Dec 2010
    Posts
    2
    Rep Power
    0

    Default Here is a slightly simpler version of the code

    Java Code:
    package example.gui;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class TextInput implements Runnable {
        LockMechanism lm = new LockMechanism();
        String value = "";
        private final String prompt;
    
        /**
         * Get a value from a swing gui
         * 
         * @param args
         * @throws InterruptedException
         */
        public static void main(String[] args) throws InterruptedException {
            String v = TextInput.getInput("Enter a number");
            System.out.println("You entered " + v);
        }
    
        /**
         * Start a swing gui in a new thread to prompt from a value
         *
         * @param prompt
         * @return
         */
        public static String getInput(String prompt) {
            TextInput ti = new TextInput(prompt);
            try {
                Thread t = new Thread(ti, "gui");
                try {
                    ti.lm.procLock.lock();
                    //start the gui thread
                    t.start();
                    //pause the current thread and wait for signal from gui
                    ti.lm.lock();
                } catch (InterruptedException ie) {
                } finally {
                    ti.lm.procLock.unlock();
                }
            } catch (Exception ex) {
                System.err.println("Exception");
            }
            return ti.value;
        }
    
        /**
         * Constructor
         * 
         * @param prompt
         */
        public TextInput(String prompt) {
            this.lm = new LockMechanism();
            this.prompt = prompt;
        }
    
        /**
         *
         */
        public void run() {
            JLabel label = new JLabel(prompt, JLabel.LEFT);
            final JFrame frame = new JFrame();
            final JTextField jTextField = new JTextField(10);
            JButton button = new JButton("Submit");
    
            button.addActionListener(new ActionListener() {
    
                //button gets clicked
                public void actionPerformed(ActionEvent e) {
                    //get the value from the textfield
                    value = jTextField.getText();
                    //resume main thread
    [COLOR="red"]                lm.unLock();[/COLOR]
                    //close the gui
                    frame.dispose();
                }
            });
    
            Box box = new Box(BoxLayout.Y_AXIS);
            box.add(label);
            box.add(jTextField);
            box.add(button);
    
            frame.getContentPane().add(box);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    
        class LockMechanism {
    
            public Lock procLock = null;
            public Condition processing = null;
            public boolean canProcess;
    
            public LockMechanism() {
                this.procLock = new ReentrantLock();
                this.processing = procLock.newCondition();
                this.canProcess = false;
            }
    
            /**
             * Pause the current thread
             *
             * @throws InterruptedException
             */
            public void lock() throws InterruptedException {
                while (!canProcess) {
                    processing.await();
                }
            }
    
            /**
             * Resume the the thread that is blocked by the lock
             */
            public void unLock() {
                canProcess = true;
                try {
    [COLOR="Red"]                processing.signalAll();[/COLOR]
                } catch (IllegalMonitorStateException imse) {
                    System.err.println("IllegalMonitorStateException");
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
            }
    
        }
    }

Similar Threads

  1. Simple Swing throws Exception in thread "AWT-EventQueue-0"
    By sultanofswing in forum AWT / Swing
    Replies: 3
    Last Post: 10-29-2010, 09:20 PM
  2. JComboBox ActionListener and Swing Thread safety
    By frenk_castle in forum AWT / Swing
    Replies: 6
    Last Post: 04-05-2010, 10:02 AM
  3. Replies: 4
    Last Post: 03-25-2010, 04:47 PM
  4. Inside a Timer thread loop,how to refresh a JTable in swing
    By neha_negi in forum Threads and Synchronization
    Replies: 3
    Last Post: 09-04-2009, 01:45 AM
  5. input prompt
    By angelbaby21 in forum New To Java
    Replies: 8
    Last Post: 08-25-2008, 04:22 AM

Tags for this Thread

Posting Permissions

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