Paid for writing

In case you like my writing and would like me to write for your website, then please leave a comment to any of my blog article, mentioning your Email Id and I will reply back. Thanks

Monday, February 2, 2009

Source code for Implementing SwingWorker Class in Java

//SwingWorkerImpl.java

The Explanation for this can be found here Explanation
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.beans.*;

public class SwingWorkerImpl implements ActionListener,PropertyChangeListener
{

JFrame mainFrame;
JTextField valueText;
JButton startButton;
final JProgressBar currentProgress;
JPanel valuePanel, progressPanel;
SwingWorkerTask swt;

public SwingWorkerImpl()
{

mainFrame=new JFrame();
mainFrame.setTitle("Swing Worker Implementation");

mainFrame.setLayout(new BorderLayout());

valueText=new JTextField(30);

startButton=new JButton("Start");

startButton.addActionListener(this);

currentProgress=new JProgressBar(0,100);

valuePanel=new JPanel();
valuePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
valuePanel.add(valueText);
valuePanel.add(startButton);

progressPanel=new JPanel();
progressPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
progressPanel.add(currentProgress);



mainFrame.add(valuePanel,BorderLayout.NORTH);
mainFrame.add(progressPanel,BorderLayout.CENTER);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setVisible(true);



}

public static void main(String args[])
{
new SwingWorkerImpl();
}

public void actionPerformed(ActionEvent ae)
{
swt=new SwingWorkerTask(valueText);
swt.addPropertyChangeListener(this);
swt.execute();
}

public void propertyChange(PropertyChangeEvent pe)
{
if("progress".equals(pe.getPropertyName()))
{
System.out.println(pe.getNewValue());
currentProgress.setValue((Integer) pe.getNewValue());
}

}
}

class SwingWorkerTask extends SwingWorker<Integer,Integer>
{
int wait;
int initialValue;
int maxValue;
int currentValue;
JTextField valueText;

public SwingWorkerTask(JTextField valueText)
{
initialValue=0;
currentValue=initialValue;
wait=1000;
this.valueText=valueText;
maxValue=Integer.parseInt(this.valueText.getText());
}

public Integer doInBackground() throws Exception
{
while(currentValue<maxValue)
{
currentValue++;
publish((Integer) currentValue);
setProgress(currentValue);
Thread.sleep(wait);
}
return maxValue;
}

public void process(List<Integer> temp)
{
for(int i:temp)
{
valueText.setText(new Integer(i).toString());
}
}

public void done()
{
valueText.setText("DONE!!! : " + maxValue);
}
}

0 comments: