import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class WorkInProgress extends JComponent{
private static final long serialVersionUID = 1L;
private int speed = 50;
private int pos = 0;
private int step = 4;
private boolean workInProgress = false;
private String progressText = null;
private String noProgressText = null;
private BufferedImage status = null;
public WorkInProgress() {
progressText = "Work in Progress";
noProgressText = "Nothing in Progress";
status = new BufferedImage(73, 20, BufferedImage.TYPE_INT_ARGB);
setForeground(Color.red);
setBackground(Color.WHITE);
setFont(new Font("monospaced", Font.BOLD + Font.ITALIC, 11));
Graphics2D g2d = status.createGraphics();
g2d.setColor(Color.BLACK);
for (int i = 0; i < 5; i++) {
g2d.fillRect(15 * i, 3, 14, 14);
}
g2d.dispose();
}
private void checkProgress() {
new Thread(new Runnable() {
public void run() {
boolean leftToRight = true;
while (isWorkInProgress()) {
repaint();
if (leftToRight) {
pos += step;
if (getWidth() - status.getWidth() < pos) {
leftToRight = false;
}
}
else {
pos -= step;
if (pos <= 0) {
leftToRight = true;
}
}
try {
Thread.sleep(speed);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
pos = 0;
repaint();
}
}).start();
}
public void paintComponent(Graphics g) {
String drawString = null;
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.setFont(getFont());
if (isWorkInProgress()) {
drawString = progressText;
g.drawImage(status, pos, getHeight() / 2 - status.getHeight() / 2, this);
}
else {
drawString = noProgressText;
}
int w = g.getFontMetrics(g.getFont()).stringWidth(drawString);
int h = g.getFontMetrics(g.getFont()).getHeight();
g.drawString(drawString, getWidth() / 2 - w / 2, getHeight() / 2 + h / 4);
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public boolean isWorkInProgress() {
return workInProgress;
}
public void setWorkInProgress(boolean workInProgress) {
this.workInProgress = workInProgress;
if (isWorkInProgress()) {
checkProgress();
}
}
public String getNoProgressText() {
return noProgressText;
}
public void setNoProgressText(String noProgressText) {
this.noProgressText = noProgressText;
}
public String getProgressText() {
return progressText;
}
public void setProgressText(String progressText) {
this.progressText = progressText;
}
public BufferedImage getStatus() {
return status;
}
public void setStatus(BufferedImage status) {
this.status = status;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 50);
WorkInProgress wip = new WorkInProgress();
frame.add(wip);
frame.setVisible(true);
wip.setWorkInProgress(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}