Tuesday, April 22, 2014
Today I am going to show you how to use the swing component - JProgressBar in your GUI application. In this article , I will also focus on how to use lambda expression in swing application. You must have seen a progress bar in many applications. It actually is used to denote graphically the amount of task or work that is completed. The basic properties are :
  • Max/Min value - A progress bar always has a maximum and a minimum value
  • Current value - This value is used to denote the current progress
The class definition of JProgressBar is
public class JProgressBar
extends JComponent
implements SwingConstants, Accessible
To know more about the JProgressBar class click here
Most often you need it while reading or writing afile. Here in our example, we will carry out a simple task where we just increase an integer value at a step of 10 and set that vakue to the progress bar. Before we assign the next value the thread sleeps for 100ms so that the progress can be viewed easily. Depending on that value a text area is updated.

The output of our demo code

Two most important things must be kept in mind whether its a simple or a complex task. In our example also we have followed that.

  • You should always carry out the task in a seperate thread. In our case generating the integer value.
  • Always update the progress bar and other swing components in event-dispatch thread only. In our case we set the progress bar value with the integer and update text area.
Also here in our code instead of creating an anonymous inner class of ActionListener and Runnable we have used Lambda Expression.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.awt.*;
import javax.swing.*;

public class JProgressBar_Demo {
    //initializing components
 private JFrame frame = new JFrame("Java Swing Examples");
    private JLabel headerLabel = new JLabel("", JLabel.CENTER);
    private JPanel 
                    controlPanel = new JPanel(),
                    contentPanel = new JPanel();
    
    private JProgressBar progressBar;
    private Task task;
    private JButton startButton;
    private JTextArea outputTextArea;

    public JProgressBar_Demo(){
       buildGUI();
    }
    
    public static void main(String[] args){
     JProgressBar_Demo  swingDemo = new JProgressBar_Demo();      
     swingDemo.showDemo();
    }   
    
    private void buildGUI(){
     frame.setSize(350,400);  //stting frame size
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setLayouts();
     //adding panels to the main panel
     contentPanel.add(headerLabel);
     contentPanel.add(controlPanel);
     frame.getContentPane().add(contentPanel);  //adding main panel to frame
     frame.setVisible(true);
    }
    //sets layout of the panels
    private void setLayouts(){
     //deliberately choosing 3 rows though have 2 components
     contentPanel.setLayout(new GridLayout(3,1));
     //to add in a directional flow
     controlPanel.setLayout(new FlowLayout());
    }
    
    public void showDemo(){
     headerLabel.setText("Component in action : JProgressBar"); 

     progressBar = new JProgressBar(0, 100);
     progressBar.setValue(0);
     progressBar.setStringPainted(true);
     startButton = new JButton("Start");

     outputTextArea = new JTextArea("",5,20);
     //adding scroller to the text-area
     JScrollPane scrollPane = new JScrollPane(outputTextArea);    
     //adding event listener
     startButton.addActionListener(
          //use of lambda expression intead new ActionListener()
       e -> {
        /* all tasks other tan component update in event listeners
           should be carried out in seperate thread */
        task = new Task();                
        task.start();
      });
     //adding components
     controlPanel.add(startButton);
     controlPanel.add(progressBar);
     controlPanel.add(scrollPane);
     frame.setVisible(true);  
    }

    //This class carries out the task when start button is clicked
    private class Task extends Thread {    
     public void run(){
      for(int i =0; i<= 100; i+=10){
       //lambda expression can use only final or pseudo-final variables
       final int progress = i;
       //update swing components in event-dispatch thread
       SwingUtilities.invokeLater(
        //lambda expression instead of new Runnable()
        () -> {
         progressBar.setValue(progress);
         outputTextArea.append(String.format("%d%% of task completed.\n", progress));
        }
       );
       try {
        Thread.sleep(100);
       } catch (InterruptedException e) {}
      }
     }
    }   
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

0 comments:

Post a Comment

Total Pageviews

Followers


Labels

Popular Posts

free counters