Page 2 of 2 FirstFirst 12
Results 21 to 21 of 21
  1. #21
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Last incarnation, works best of all previous:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.beans.*;
    import java.io.*;
    import java.util.*;
    import java.util.concurrent.*;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ActivityQueue2b extends JPanel {
    
       private LinkedList<SCPActivity> queue;
       private JProgressBar pBar;
       private JLabel progLabel;
       private JTextArea console;
       private static final String newline = "\n";
       //private int total;
    
       public ActivityQueue2b(ArrayList<SCPActivity> queue) {
          this.queue = new LinkedList<SCPActivity>();
    
         // total = 0;
    
          pBar = new JProgressBar(0, 100);
          pBar.setValue(0);
          pBar.setStringPainted(true);
    
          progLabel = new JLabel("");
          console = new JTextArea(25, 50);
          console.setEditable(false);
    
          for (SCPActivity act : queue) {
             addToQueue(act);
          }
    
          JPanel buttonPanel = new JPanel();
          setLayout(new BorderLayout());
          buttonPanel.add(new JButton(new StartAction()));
          buttonPanel.add(progLabel);
          buttonPanel.add(pBar);
    
          add(buttonPanel, BorderLayout.SOUTH);
          add(new JScrollPane(console), BorderLayout.CENTER);
       }
    
       /**
        * Method called in order to show the UI and set up the ActivityQueue
        * 
        * @param queue
        *           - ArrayList passed into the ActivityQueue constructor
        */
       public static void createAndShowGui(ArrayList<SCPActivity> queue) {
          JFrame frame = new JFrame("Activity Console");
          frame.getContentPane().add(new ActivityQueue2b(queue));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(750, 600);
          frame.pack();
          frame.setResizable(false);
          frame.setLocation(1700, 200);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       /**
        * Adds the activity parameter to the queue if it doesn't already exist
        * 
        * @param activity
        *           - an activity that will be added to the queue
        */
       public void addToQueue(SCPActivity activity) {
          if (!queue.contains(activity)) {
             queue.add(activity);
             writeToConsole("*" + activity.getActivityID() + " added to queue.");
          }
    
          setProgLabel("Number of items in queue: " + queue.size()
                + " | Status: waiting...");
       }
    
       /**
        * Updates all indicators that display the overall progress of the activity
        * execution
        * 
        * @param count
        * @param totals
        */
       public void updateProgressIndicators(int totals, int count) {
          String status = "";
    
          int progress = Utilities.getPercentage(totals - count, totals);
    
          if (progress >= 100)
             status = "complete!";
          else
             status = "executing...";
    
          setProgLabel("Number of items in queue: " + queue.size() + " | Status: "
                + status);
          pBar.setValue(progress);
       }
    
       /**
        * Writes the provided message to the console then prints a new line
        * 
        * @param message
        *           - the message to print to the console
        */
       public void writeToConsole(String message) {
          if (!message.equals(""))
             console.append(message + newline);
       }
    
       /**
        * Sets the progress label to the value of 'message'
        * 
        * @param message
        *           - the message which to set the progress label
        */
       public void setProgLabel(String message) {
          if (!(message.equals("")))
             progLabel.setText(message);
       }
    
       /**
        * Private inner class that is used to execute the activities in the queue
        */
       private class StartAction extends AbstractAction {
    
          public StartAction() {
             super("Execute");
          }
    
          @Override
          public void actionPerformed(final ActionEvent e) {
             if (queue.size() > 0) {
                ((JButton)e.getSource()).setEnabled(false);
                new SwingWorker<Void, String>() {
                   private int taskCount = queue.size();
                   private CountDownLatch latch = new CountDownLatch(queue.size());
                   private ExecutorService pool = Executors
                         .newFixedThreadPool(taskCount);
                   private Map<MyTask2b, Future<String>> taskFutureMap = new HashMap<MyTask2b, Future<String>>();
    
                   @Override
                   protected Void doInBackground() throws Exception {
                      PropertyChangeListener myPropChngListener = new PropertyChangeListener() {
                         public void propertyChange(PropertyChangeEvent evt) {
                            String name = evt.getPropertyName();
                            if (name.equals(MyTask2b.LINE)) {
                               MyTask2b task = (MyTask2b) evt.getSource();
                               publish(task.getLine());
                            }
                         }
                      };
    
                      while (queue.size() > 0) {
                         SCPActivity act = queue.pop();
                         MyTask2b task = new MyTask2b(act.getActivityID(), latch,
                               act);
                         task.addPropertyChangeListener(myPropChngListener);
                         taskFutureMap.put(task, pool.submit(task));
                      }
    
                      latch.await();
    
                      for (Future<String> future : taskFutureMap.values()) {
                         try {
                            String text = future.get() + " -- DONE";
                            publish(text);
                         } catch (InterruptedException e) {
                            e.printStackTrace();
                         } catch (ExecutionException e) {
                            e.printStackTrace();
                         }
                      }
                      return null;
                   }
    
                   @Override
                   protected void process(List<String> chunks) {
                      for (String chunk : chunks) {
                         updateProgressIndicators(taskCount, (int) latch.getCount());
                         console.append(chunk + "\n");
                      }
                   }
    
                   @Override
                   protected void done() {
                      updateProgressIndicators(taskCount, (int) latch.getCount());
                      ((JButton)e.getSource()).setEnabled(true);
                   }
    
                }.execute();
    
             } else {
    
                writeToConsole("There are no activities in the queue. Please select modules to "
                      + "execute or wait for"
                      + newline
                      + "the queue to populate."
                      + newline);
             }
          }
       }
    
       public static void main(String[] args) {
    
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                ArrayList<SCPActivity> q = new ArrayList<SCPActivity>();
                SCPping act = new SCPping("google.com");
                q.add(act);
                act = new SCPping("yahoo.com");
                q.add(act);
                act = new SCPping("facebook.com");
                q.add(act);
    
                createAndShowGui(q);
             }
          });
       }
    }
    
    class MyTask2b implements Callable<String> {
       public static final String STATE = "state";
       public static final String LINE = "line";
       private String text;
       private CountDownLatch latch;
       private PropertyChangeSupport propChngSupport = new PropertyChangeSupport(
             this);
       private SwingWorker.StateValue state = SwingWorker.StateValue.PENDING;
       private SCPActivity act;
       private String line = "";
    
       public MyTask2b(String text, CountDownLatch latch, SCPActivity act) {
          this.text = text;
          this.latch = latch;
          this.act = act;
       }
    
       @Override
       public String call() throws Exception {
          setLine("activity started");
          setState(SwingWorker.StateValue.STARTED);
    
          while (!(state.equals(SwingWorker.StateValue.DONE))) {
             int instances = Utilities.getNumberOfProcesses("ping.exe");
             if (instances < 2) {
                setLine("activity executing");
                act.execute();
                InputStream stream = act.getStream();
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                      stream));
    
                try {
                   while (!reader.ready()) {
                   }
                   String text = "";
                   while ((text = reader.readLine()) != null) {
                      setLine(text);
                   }
                } catch (IOException e1) {
                   e1.printStackTrace();
                }
                latch.countDown();
                setState(SwingWorker.StateValue.DONE);
             }
          }
          return text;
       }
    
       private void setState(SwingWorker.StateValue newValue) {
          SwingWorker.StateValue oldValue = this.state;
          this.state = newValue;
          PropertyChangeEvent evt = new PropertyChangeEvent(this, STATE, oldValue,
                newValue);
          propChngSupport.firePropertyChange(evt);
       }
    
       private void setLine(String newValue) {
          String oldValue = this.line;
          this.line = newValue;
          PropertyChangeEvent evt = new PropertyChangeEvent(this, LINE, oldValue,
                newValue);
          propChngSupport.firePropertyChange(evt);
       }
    
       public String getLine() {
          return act.getActivityID() + ": " + line;
       }
    
       public void addPropertyChangeListener(PropertyChangeListener listener) {
          propChngSupport.addPropertyChangeListener(listener);
       }
    
       public void removePropertyChangeListener(PropertyChangeListener listener) {
          propChngSupport.removePropertyChangeListener(listener);
       }
    }
    Last edited by Fubarable; 08-06-2011 at 01:47 PM.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. Center text in a JComponent?
    By Zman3359 in forum New To Java
    Replies: 4
    Last Post: 04-17-2011, 10:44 PM
  2. Question on getGraphics() in a JComponent
    By Shayke_ in forum Java 2D
    Replies: 2
    Last Post: 02-10-2011, 07:31 PM
  3. Replies: 2
    Last Post: 10-01-2010, 07:18 PM
  4. SetBackground for JComponent
    By tulasi.neppali in forum AWT / Swing
    Replies: 5
    Last Post: 09-12-2010, 10:14 PM
  5. Random size of JComponent
    By Karl-von-bahnhof in forum AWT / Swing
    Replies: 0
    Last Post: 04-13-2010, 08:14 PM

Posting Permissions

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