Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  jDTAUS - DTAUS fileformat.
   *  Copyright (c) 2005 Christian Schulte <cs@schulte.it>
   *
   *  This library is free software; you can redistribute it and/or
   *  modify it under the terms of the GNU Lesser General Public
   *  License as published by the Free Software Foundation; either
   *  version 2.1 of the License, or any later version.
   *
  *  This library is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  *  Lesser General Public License for more details.
  *
  *  You should have received a copy of the GNU Lesser General Public
  *  License along with this library; if not, write to the Free Software
  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  *
  */
 package org.jdtaus.core.monitor.util;
 
 import java.awt.Frame;
 import java.util.Date;
 import java.util.Map;
 import  org.jdtaus.core.container.ContainerFactory;
 import  org.jdtaus.core.container.ContextFactory;
 import  org.jdtaus.core.container.ContextInitializer;
 import  org.jdtaus.core.container.Implementation;
 import  org.jdtaus.core.container.ModelFactory;
 import  org.jdtaus.core.container.Properties;
 import  org.jdtaus.core.container.Property;
 import  org.jdtaus.core.container.PropertyException;
 import  org.jdtaus.core.logging.spi.Logger;
 import  org.jdtaus.core.monitor.Task;
 import  org.jdtaus.core.monitor.TaskEvent;
 import  org.jdtaus.core.monitor.TaskListener;

TaskListener displaying progress using a Swing dialog.

Author(s):
Christian Schulte
Version:
$Id: SwingProgressMonitor.java 4336 2007-08-23 01:35:00Z schulte2005 $
See also:
onTaskEvent(TaskEvent)
 
 public final class SwingProgressMonitor implements TaskListener
 {
     //--Implementation----------------------------------------------------------
 
 // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausImplementation
     // This section is managed by jdtaus-container-mojo.
 
    
Meta-data describing the implementation.
 
     private static final Implementation META =
         ModelFactory.getModel().getModules().
         getImplementation(SwingProgressMonitor.class.getName());
 // </editor-fold>//GEN-END:jdtausImplementation
 
     //----------------------------------------------------------Implementation--
     //--Constructors------------------------------------------------------------
 
 // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausConstructors
     // This section is managed by jdtaus-container-mojo.
 
    
Initializes the properties of the instance.

Parameters:
meta the property values to initialize the instance with.
Throws:
NullPointerException if meta is null.
 
     private void initializeProperties(final Properties meta)
     {
         Property p;
 
         if(meta == null)
        {
            throw new NullPointerException("meta");
        }
        p = meta.getProperty("millisToPopup");
        this. = ((java.lang.Integerp.getValue()).intValue();
        p = meta.getProperty("millisToDecideToPopup");
        this. = ((java.lang.Integerp.getValue()).intValue();
    }
// </editor-fold>//GEN-END:jdtausConstructors
    //------------------------------------------------------------Constructors--
    //--Dependencies------------------------------------------------------------
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausDependencies
    // This section is managed by jdtaus-container-mojo.

    
Configured Logger implementation.
    private transient Logger _dependency0;

    
Gets the configured Logger implementation.

Returns:
the configured Logger implementation.
    private Logger getLogger()
    {
        Logger ret = null;
        if(this. != null)
        {
            ret = this.;
        }
        else
        {
            ret = (Logger) ContainerFactory.getContainer().
                getDependency(SwingProgressMonitor.class,
                "Logger");
            if(ModelFactory.getModel().getModules().
                getImplementation(SwingProgressMonitor.class.getName()).
                getDependencies().getDependency("Logger").
                isBound())
            {
                this. = ret;
            }
        }
        if(ret instanceof ContextInitializer && !((ContextInitializer) ret).
            isInitialized(ContextFactory.getContext()))
        {
            ((ContextInitializer) ret).initialize(ContextFactory.getContext());
        }
        return ret;
    }
// </editor-fold>//GEN-END:jdtausDependencies
    //------------------------------------------------------------Dependencies--
    //--Properties--------------------------------------------------------------
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:jdtausProperties
    // This section is managed by jdtaus-container-mojo.

    
Property millisToPopup.

Serial:
    private int _millisToPopup;

    
Gets the value of property millisToPopup.

Returns:
the value of property millisToPopup.
    public int getMillisToPopup()
    {
        return this.;
    }

    
Property millisToDecideToPopup.

Serial:
    private int _millisToDecideToPopup;

    
Gets the value of property millisToDecideToPopup.

Returns:
the value of property millisToDecideToPopup.
    public int getMillisToDecideToPopup()
    {
        return this.;
    }
// </editor-fold>//GEN-END:jdtausProperties
    //--------------------------------------------------------------Properties--
    //--TaskListener------------------------------------------------------------

    

This method controls a dialog displaying a panel for each task showing the progress of that task optionally providing a cancel button if the corresponding task is cancelable. The dialog will show up only if the operation performed by at least one task is believed to run longer than specified by property millisToPopup. Property millisToDecideToPopup controls the number of milliseconds to pass before all currently running tasks are checked for theire duration. Properties millisToDecideToPopup and millisToPopup are used in the same way as specified for Swing's javax.swing.ProgressMonitor. The default for property millisToDecideToPopup is 500ms and the default for property millisToPopup is 2000ms.

Parameters:
event the event send by a Task.
    public synchronized void onTaskEvent(final TaskEvent event)
    {
        if(event != null)
        {
            final MonitorState state;
            switch(event.getType())
            {
                case TaskEvent.STARTED:
                    final ActionListener cancelListener =
                        new ActionListener()
                    {
                        public void actionPerformed(
                            final ActionEvent e)
                        {
                            if(!event.getTask().isCancelled())
                            {
                                event.getTask().setCancelled(true);
                            }
                        }
                    };
                    state = new MonitorState(event.getTask(),
                        new ProgressPanel(), cancelListener,
                        System.currentTimeMillis());
                    final TitledBorder border =
                        BorderFactory.createTitledBorder(
                        state.task.getDescription().getText(
                        Locale.getDefault()));
                    state.panel.setBorder(border);
                    if(state.task.getProgressDescription() != null)
                    {
                        state.panel.getProgressDescriptionLabel().
                            setText(
                            state.task.getProgressDescription().
                            getText(Locale.getDefault()));
                    }
                    else
                    {
                        state.panel.getProgressDescriptionLabel().
                            setVisible(false);
                    }
                    state.panel.getProgressBar().setIndeterminate(
                        state.task.isIndeterminate());
                    if(!state.task.isIndeterminate())
                    {
                        state.panel.getProgressBar().setMinimum(
                            state.task.getMinimum());
                        state.panel.getProgressBar().setMaximum(
                            state.task.getMaximum());
                        state.panel.getProgressBar().setValue(
                            state.task.getProgress());
                    }
                    state.panel.getCancelButton().setVisible(
                        state.task.isCancelable());
                    state.panel.getCancelButton().addActionListener(
                        state.cancelListener);
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            state.panel.setVisible(false);
                            getDialog().add(state.panel);
                        }
                    });
                    if(.put(state.taskstate) != null)
                    {
                        throw new IllegalStateException(
                            SwingProgressMonitorBundle.
                            getTaskAlreadyStartedMessage(Locale.getDefault()).
                            format(new Object[] {
                            state.task.getDescription().getText(
                                Locale.getDefault()),
                            new Date(state.task.getTimestamp()) }));
                    }
                    break;
                case TaskEvent.CHANGED_STATE:
                    state = (MonitorState.get(event.getTask());
                    assert state != null :
                        "Expected a started task.";
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            if(!state.task.isIndeterminate())
                            {
                                state.panel.getProgressBar().setValue(
                                    state.task.getProgress());
                            }
                            if(state.task.getProgressDescription() != null)
                            {
                                final String oldText =
                                    state.panel.getProgressDescriptionLabel().
                                    getText();
                                final String newText =
                                    state.task.getProgressDescription().
                                    getText(Locale.getDefault());
                                if(oldText == null ||
                                    !oldText.equals(newText))
                                {
                                    state.panel.getProgressDescriptionLabel().
                                        setText(newText);
                                }
                                if(!state.panel.getProgressDescriptionLabel().
                                    isVisible())
                                {
                                    state.panel.getProgressDescriptionLabel().
                                        setVisible(true);
                                }
                            }
                            else
                            {
                                if(state.panel.getProgressDescriptionLabel().
                                    isVisible())
                                {
                                    state.panel.getProgressDescriptionLabel().
                                        setVisible(false);
                                }
                            }
                        }
                    });
                    break;
                case TaskEvent.ENDED:
                    state = (MonitorState.remove(event.getTask());
                    assert state != null :
                        "Expected a started task.";
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            state.panel.getCancelButton().
                                removeActionListener(state.cancelListener);
                            getDialog().remove(state.panel);
                        }
                    });
                    break;
                default:
                    getLogger().warn(SwingProgressMonitorBundle.
                        getUnknownEventTypeMessage(Locale.getDefault()).
                        format(new Object[] { new Integer(event.getType()) }));
            }
        }
        if(this..size() > 0)
        {
            final long now = System.currentTimeMillis();
            if(this. == )
            {
                this. = now;
            }
            else if(now - this. >
                this.getMillisToDecideToPopup())
            {
                // If any task's operation runs longer than millisToPopup
                // show the dialog.
                for(Iterator it = this..entrySet().iterator();
                it.hasNext();)
                {
                    final Map.Entry entry = (Map.Entryit.next();
                    final MonitorState state =
                        (MonitorStateentry.getValue();
                    if(!state.task.isIndeterminate())
                    {
                        if(state.task.getProgress() > state.task.getMinimum())
                        {
                            final long predicted = (now - state.startMillis) *
                                (state.task.getMaximum() -
                                state.task.getMinimum()) /
                                (state.task.getProgress() -
                                state.task.getMinimum());
                            if(predicted > getMillisToPopup() &&
                                !state.panel.isVisible())
                            {
                                // If the task is believed to last longer than
                                // millisToPopup add the panel to the dialog.
                                SwingUtilities.invokeLater(new Runnable()
                                {
                                    public void run()
                                    {
                                        state.panel.setVisible(true);
                                        getDialog().pack();
                                        if(!getDialog().isVisible())
                                        {
                                            getDialog().setLocationRelativeTo(
                                                getParent());
                                            getDialog().setVisible(true);
                                        }
                                    }
                                });
                            }
                        }
                    }
                    else if(!state.panel.isVisible() &&
                        now - state.task.getTimestamp() >
                        this.getMillisToPopup())
                    { // Only show long running indeterminate tasks.
                        SwingUtilities.invokeLater(new Runnable()
                        {
                            public void run()
                            {
                                state.panel.setVisible(true);
                                getDialog().pack();
                                if(!getDialog().isVisible())
                                {
                                    getDialog().setLocationRelativeTo(
                                        getParent());
                                    getDialog().setVisible(true);
                                }
                            }
                        });
                    }
                }
            }
        }
        else
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    closeDialog();
                }
            });
            this. = ;
        }
    }
    //------------------------------------------------------------TaskListener--
    //--SwingProgressMonitor----------------------------------------------------

    
State of a Task being monitored.
    private static final class MonitorState
    {
        
The Task being monitored.
        final Task task;

        
The panel to use for disaplying progress of task.
        final ProgressPanel panel;

        
The time task got started.
        final long startMillis;

        
ActionListener listening for the cancel button.
        final ActionListener cancelListener;

        
Creates a new MonitorState instance.

Parameters:
task the Task being monitored.
panel the panel to use for displaying progress of task.
startMillis the time task got started.
cancelListener the listener to listen for the cancel button.
        MonitorState(final Task taskfinal ProgressPanel panel,
            final ActionListener cancelListenerfinal long startMillis)
        {
            this. = task;
            this. = panel;
            this. = cancelListener;
            this. = startMillis;
        }
    }

    
The current parent component to use when displaying progress.
    private Component parent;

    
Maps Task instances to TaskMonitorState instances.
    private final Map tasks = new HashMap(100);

    
The dialog displaying progress of all Tasks.
    private ProgressDialog dialog;

    
The time the decision was made to popup a dialog, if an operation of any of the tasks being monitored would take longer than millisToPopup.
    private long popupDecisionMillis = ;
    private static final long NO_POPUPDECISION = .;

    
Creates a new SwingProgressMonitor instance taking the parent component to use when displaying progress.

Parameters:
parent the parent component to use when displaying progress.
Throws:
NullPointerException if parent is null.
HeadlessException if this class is used in an environment not providing a keyboard, display, or mouse.
See also:
onTaskEvent(TaskEvent)
    public SwingProgressMonitor(final Component parent)
    {
        if(parent == null)
        {
            throw new NullPointerException("parent");
        }
        if(GraphicsEnvironment.isHeadless())
        {
            throw new HeadlessException();
        }
        this.initializeProperties(.getProperties());
        this.assertValidProperties();
        this. = parent;
    }

    
Creates a new SwingProgressMonitor instance taking the parent component to use when displaying progress and configuration for how long to wait before showing the progress dialog.

Parameters:
parent the parent component to use when displaying progress.
millisToDecideToPopup the number of milliseconds which have to pass before the duration of any currently running task is computed.
millisToPopup the number of milliseconds at least one task has to run before the progress dialog shows up.
Throws:
NullPointerException if parent is null.
PropertyException if either millisToDecideToPopup or millisToPopup is negative or zero.
HeadlessException if this class is used in an environment not providing a keyboard, display, or mouse.
See also:
onTaskEvent(TaskEvent)
    public SwingProgressMonitor(final Component parent,
        final int millisToDecideToPopupfinal int millisToPopup)
    {
        if(parent == null)
        {
            throw new NullPointerException("parent");
        }
        if(GraphicsEnvironment.isHeadless())
        {
            throw new HeadlessException();
        }
        this.initializeProperties(.getProperties());
        this. = millisToDecideToPopup;
        this. = millisToPopup;
        this.assertValidProperties();
        this. = parent;
    }

    
Gets the parent component for any progress displays.

Returns:
the parent component for any progress displays.
    public Component getParent()
    {
        return this.;
    }

    
Sets the parent component to be used by any progress displays.

Parameters:
parent the parent component to be used by any progress displays.
Throws:
NullPointerException if parent is null.
    public void setParent(final Component parent)
    {
        if(parent == null)
        {
            throw new NullPointerException("parent");
        }
        this. = parent;
    }

    
Checks configured properties.

Throws:
PropertyException for illegal property values.
    private void assertValidProperties()
    {
        if(this.getMillisToDecideToPopup() < 0)
        {
            throw new PropertyException("millisToDecideToPopup",
                Integer.toString(this.getMillisToDecideToPopup()));
        }
        if(this.getMillisToPopup() < 0)
        {
            throw new PropertyException("millisToPopup",
                Integer.toString(this.getMillisToPopup()));
        }
    }

    
Gets the dialog displaying progress of all Tasks.

Returns:
the dialog displaying progress of all Tasks.
    private synchronized ProgressDialog getDialog()
    {
        if(this. == null)
        {
            final Window window = this.getWindowForComponent(this.getParent());
            if(window instanceof Frame)
            {
                this. = new ProgressDialog((Framewindow);
            }
            else if(window instanceof Dialog)
            {
                this. = new ProgressDialog((Dialogwindow);
            }
        }
        return this.;
    }

    
Closes and disposes the dialog.
    private synchronized void closeDialog()
    {
        if(this. != null)
        {
            this..setVisible(false);
            this..dispose();
            this. = null;
        }
    }

    
Returns the specified component's toplevel Frame or Dialog.

Parameters:
parentComponent the Component to check for a Frame or Dialog.
Returns:
the Frame or Dialog that contains parentComponent, or the default frame if the component is null, or does not have a valid Frame or Dialog parent.
Throws:
HeadlessException if GraphicsEnvironment.isHeadless() returns true.
See also:
java.awt.GraphicsEnvironment.isHeadless
    private Window getWindowForComponent(final Component parentComponent)
    throws HeadlessException
    {
        Window window = JOptionPane.getRootFrame();
        if (parentComponent != null)
        {
            if(parentComponent instanceof Frame ||
                parentComponent instanceof Dialog)
            {
                window = (WindowparentComponent;
            }
            else
            {
                this.getWindowForComponent(parentComponent.getParent());
            }
        }
        return window;
    }
    //----------------------------------------------------SwingProgressMonitor--
JPanel displaying the progress for a Task.

Author(s):
Christian Schulte
Version:
$Id: SwingProgressMonitor.java 4336 2007-08-23 01:35:00Z schulte2005 $
class ProgressPanel extends JPanel
    //--ProgressPanel-----------------------------------------------------------

    
JLabel for displaying a Tasks progress description.
    private final JLabel progressDescriptionLabel;

    
JProgressBar for displaying a Tasks progress.
    private final JProgressBar progressBar;

    
JButton for cancelling a Task.
    private final JButton cancelButton;

    
Creates a new ProgressPanel instance.
    {
        this. = new JLabel();
        this. = new JProgressBar();
        this. = new JButton();
        this..setText(
            UIManager.getString("OptionPane.cancelButtonText"));
        this.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = .;
        c.anchor = .;
        c.weightx = 1.0D;
        c.fill = .;
        c.insets = new Insets(10, 25, 10, 25);
        this.add(this.getProgressBar(), c);
        c = new GridBagConstraints();
        c.gridwidth = .;
        c.anchor = .;
        c.weightx = 1.0D;
        c.fill = .;
        c.insets = new Insets(2, 25, 2, 25);
        this.add(this.getProgressDescriptionLabel(), c);
        c = new GridBagConstraints();
        c.gridheight = .;
        c.anchor = .;
        c.weighty = 1.0D;
        c.insets = new Insets(2, 5, 2, 5);
        this.add(this.getCancelButton(), c);
    }
    {
        return this.;
    }
    {
        return this.;
    }
    {
        return this.;
    }
    //-----------------------------------------------------------ProgressPanel--
JDialog displaying the progress of all Tasks.

Author(s):
Christian Schulte
Version:
$Id: SwingProgressMonitor.java 4336 2007-08-23 01:35:00Z schulte2005 $
class ProgressDialog extends JDialog
    //--ProgressDialog----------------------------------------------------------

    
Creates a new ProgressDialog taking the owning frame.

Parameters:
owner the frame owning the dialog.
    ProgressDialog(final Frame owner)
    {
        super(ownertrue);
        this.initializeDialog();
    }

    
Creates a new ProgressDialog taking the owning dialog.

Parameters:
owner the dialog owning the dialog.
    ProgressDialog(final Dialog owner)
    {
        super(ownertrue);
        this.initializeDialog();
    }

    
Sets the layout and title of the dialog.
    private void initializeDialog()
    {
        this.getContentPane().setLayout(new GridBagLayout());
        this.setTitle(UIManager.getString("ProgressMonitor.progressText"));
    }
    void add(final ProgressPanel panel)
    {
        if(panel == null)
        {
            throw new NullPointerException("panel");
        }
        final GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = .;
        c.anchor = .;
        c.weightx = 1.0D;
        c.weighty = 1.0D;
        c.fill = .;
        this.getContentPane().add(panelc);
    }
    void remove(final ProgressPanel panel)
    {
        if(panel == null)
        {
            throw new NullPointerException("panel");
        }
        this.getContentPane().remove(panel);
        this.validate();
    }
    //----------------------------------------------------------ProgressDialog--