Results 1 to 7 of 7
  1. #1
    jameskelly is offline Member
    Join Date
    Nov 2010
    Posts
    4
    Rep Power
    0

    Default Using threads in a graphical program

    This is about threads but I posted here because it's really basic.

    So I've read a tutorial on concurrency but I'm not sure where exactly I should use threads within the program. I'm not looking for code just an explanation.

    I've been messing around with this application to try things out. It's just an extension of a JPanel that draws squares when you click, but let's say first you clicked all your points, then pressed a button that did all the drawing. How could I make that a thread, so then someone else could click points on the canvas and press the button when they wanted to get their squares (in a separate thread)?

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

    Default

    Quote Originally Posted by jameskelly View Post
    How could I make that a thread, so then someone else could click points on the canvas and press the button when they wanted to get their squares (in a separate thread)?
    Please clarify. Perhaps it's me, but I don't quite make sense of what you're trying to do just yet or why you need a separate thread. Also, many here are not going to click on links.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,784
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by jameskelly View Post
    This is about threads but I posted here because it's really basic.

    So I've read a tutorial on concurrency but I'm not sure where exactly I should use threads within the program. I'm not looking for code just an explanation.

    I've been messing around with this application to try things out. It's just an extension of a JPanel that draws squares when you click, but let's say first you clicked all your points, then pressed a button that did all the drawing. How could I make that a thread, so then someone else could click points on the canvas and press the button when they wanted to get their squares (in a separate thread)?
    Note, if you're using Swing or AWT there's already a Thread running: Swing's or AWT't event dispatching thread. When your MouseListener or ActionListener receicves an event it runs in that event dispatching thread (EDT). Your 'rectangle drawing' method or class object isn't stateless: it receives points and when it's ready it dumps a representation ready for drawing in the paintComponent( ... ) method that also runs in the EDT. That method is called by Swing (or AWT) when you call the repaint() method. So careful scheduling should do the job without introducing yet another thread.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    jameskelly is offline Member
    Join Date
    Nov 2010
    Posts
    4
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Please clarify. Perhaps it's me, but I don't quite make sense of what you're trying to do just yet or why you need a separate thread. Also, many here are not going to click on links.
    Well mutlithreading isn't necessary I'm just practicing here.

    So you have a JPanel, you can click and those coordinates are stored. Then you can click a button which creates a thread that performs the actual drawing of the squares. Then someone else can click some more, press the button again and new squares are created in a different thread.

    This link is safe everyone it's from tech recipes.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    As Josh notes, all code that occurs in Swing itself, such as responding to mouse clicks or button presses, and all painting in the GUI must be done on the EDT, or Event Dispatch Thread, Swing's main thread responsible for these things. You'll usually use a background thread when you want to perform a long process off of the GUI such as when you want to upload a large image file or access a database.

    But if you want to modify the file in the link, go ahead and give it a try, and then please feel free to post your attempt here.

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

    Default

    Here's some code I dug up that shows what happens when you try to do a long-running process on the EDT versus on a background thread:

    Java Code:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    
    import javax.swing.*;
    
    public class TestProgressBar {
       private static void createAndShowUI() {
          JFrame frame = new JFrame("TestProgressBar");
          frame.getContentPane().add(new TestPBGui().getMainPanel());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    class TestPBGui {
       private JPanel mainPanel = new JPanel();
    
       public TestPBGui() {
          JButton noBackgroundThreadBtn = new JButton("Progress Bar w/out Background Thread");
          JButton backgroundThreadBtn = new JButton("Progress Bar with Background Thread");
    
          noBackgroundThreadBtn.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                noBackgroundThreadActionPerformed();
             }
          });
          backgroundThreadBtn.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                backgroundThreadActionPerformed();
             }
          });
    
          mainPanel.add(noBackgroundThreadBtn);
          mainPanel.add(backgroundThreadBtn);
       }
    
       private void noBackgroundThreadActionPerformed() {
          Window thisWin = SwingUtilities.getWindowAncestor(mainPanel);
          final JDialog progressDialog = new JDialog(thisWin, "Uploading...");
          createProgressBar(progressDialog);
    
          Task task = new Task("No background thread");
          task.execute();
    
          progressDialog.setVisible(true);
          while (!task.isDone()) {
          }
          progressDialog.dispose();
       }
    
       private void backgroundThreadActionPerformed() {
          Window thisWin = SwingUtilities.getWindowAncestor(mainPanel);
          final JDialog progressDialog = new JDialog(thisWin, "Uploading...");
          final JProgressBar bar = createProgressBar(progressDialog);
    
          final Task task = new Task("Background Thread");
          task.addPropertyChangeListener(new PropertyChangeListener() {
             public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equalsIgnoreCase("progress")) {
                   int progress = task.getProgress();
                   if (progress == 0) {
                      bar.setIndeterminate(true);
                   } else {
                      bar.setIndeterminate(false);
                      progressDialog.dispose();
                   }
                }
             }
          });
          task.execute();
    
          progressDialog.setVisible(true);
       }
    
       private JProgressBar createProgressBar(final JDialog progressDialog) {
          JPanel contentPane = new JPanel();
          contentPane.setPreferredSize(new Dimension(300, 100));
          final JProgressBar bar = new JProgressBar(0, 100);
          bar.setIndeterminate(true);
          contentPane.add(bar);
          progressDialog.setContentPane(contentPane);
          progressDialog.pack();
          progressDialog.setLocationRelativeTo(null);
          return bar;
       }
    
       public JPanel getMainPanel() {
          return mainPanel;
       }
    }
    
    class Task extends SwingWorker<Void, Void> {
    
       private static final long SLEEP_TIME = 4000;
       private String text;
    
       public Task(String text) {
          this.text = text;
       }
    
       @Override
       public Void doInBackground() {
          setProgress(0);
          try {
             // imitate a long-running task
             Thread.sleep(SLEEP_TIME);
          } catch (InterruptedException e) {
          }
          setProgress(100);
          return null;
       }
    
       @Override
       public void done() {
          System.out.println(text + " is done");
          Toolkit.getDefaultToolkit().beep();
       }
    
    }

  7. #7
    jameskelly is offline Member
    Join Date
    Nov 2010
    Posts
    4
    Rep Power
    0

    Default

    Thanks for that I'll try reading through it and make sense of it.

Similar Threads

  1. Graphical Java Developer
    By ALATECjobs in forum Jobs Offered
    Replies: 2
    Last Post: 09-29-2009, 12:24 AM
  2. Graphical query
    By Alex j in forum Introductions
    Replies: 0
    Last Post: 04-07-2009, 07:48 AM
  3. Graphical view of an array
    By ventrue in forum New To Java
    Replies: 2
    Last Post: 02-13-2009, 08:31 PM
  4. Graphical Ftp client
    By Java Tip in forum java.net
    Replies: 0
    Last Post: 04-07-2008, 09:10 PM
  5. Replies: 0
    Last Post: 11-29-2007, 09:19 PM

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
  •