NAME

FLTK::Cookbook::ProgressBar::Process - Update the user while processing in the background

Description

Demonstrates how to update a progress bar within a cpu intensive operation without threads.

The Code

use strict;
use warnings;
use FLTK qw[check run];

# Button callback
sub btn_cb {
    my ($self, $w) = @_;

    # Deactivate the button
    $self->deactivate();    # prevent button from being pressed again
    check();                # give fltk some cpu to gray out button

    # Make the progress bar
    $w->begin();            # add progress bar to parent window.
    my $progress = FLTK::ProgressBar->new(10, 50, 200, 30);
    $progress->minimum(0);  # set progress bar attribs.
    $progress->maximum(1);
    $w->end();              # end of adding to window

    # Computation loop..
    for my $t (1 .. 20) {
        $progress->position($t / 20);    # update progress bar
        check();     # give fltk some cpu to update the screen
        sleep(1);    # 'your stuff' that's compute intensive
        last if !$w->visible;    # stop if the window has closed
    }

    # Cleanup
    $progress
        ->destroy;    # remove progress bar from window and deallocate it
    $self->activate();   # reactivate button
    $w->redraw();        # tell window to redraw now that progress removed
}

# main
my $win = FLTK::Window->new(220, 90);
my $btn = FLTK::Button->new(10, 10, 100, 25, 'Press');
$btn->callback(\&btn_cb, $win);
$win->add($btn);
$win->resizable($win);
$win->show();
exit run();

Awknowlegements

Code based on the work of Greg Ercolano

Author

Sanko Robinson <sanko@cpan.org> - http://sankorobinson.com/

License and Legal

Copyright (C) 2008-2009 by Sanko Robinson <sanko@cpan.org>

This program is free software; you can redistribute it and/or modify it under the terms of The Artistic License 2.0. See the LICENSE file included with this distribution or http://www.perlfoundation.org/artistic_license_2_0. For clarification, see http://www.perlfoundation.org/artistic_2_0_notes.

When separated from the distribution, all original POD documentation is covered by the Creative Commons Attribution-Share Alike 3.0 License. See http://creativecommons.org/licenses/by-sa/3.0/us/legalcode. For clarification, see http://creativecommons.org/licenses/by-sa/3.0/us/.