How do I write a status bar in AWT/Swing?

Christopher Brind

Here's something I just knocked up. If you use this example remember to add your main component to the CENTER of the frame's content pane.

[FAQ Manager Note] Note that you can have anything you want in the south part of the frame. In this example, a simple JLabel is used, but you could also use a JPanel that contains several fields, each of which you update independently.

Note that the Thread.sleep isn't anything special here -- he's using it to "simulate" some real processing.

The same strategy would apply for AWT components as well.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class StatusFrame extends JFrame {

    private final JLabel status = new JLabel("Status Frame 1.0");

    public StatusFrame(String s) {

        super(s);

        Container c = super.getContentPane();
        c.setLayout(new BorderLayout());

        status.setBorder(new EtchedBorder());
        c.add(status, BorderLayout.SOUTH);
    }

    public void setStatus(String s) {
        status.setText(s);
    }

    public static void main(String asArgs[]) throws InterruptedException {

        StatusFrame sf = new StatusFrame("my status frame");
        sf.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        sf.setSize(800, 600);
        sf.setVisible(true);

        sf.setStatus("For Help, press F1");
        Thread.sleep(1000);

        // ... do some stuff
        sf.setStatus("Doing some stuff...");
        Thread.sleep(1000);

        // ... finished doing some stuff.
        sf.setStatus("For Help, press F1");
    }


}


Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact