Question

How can you display text inside a JProgressBar? i.e. "000/100"

progPanel.setBorder(BorderFactory. createEmptyBorder(10,10,10,10));
timerBar = new JProgressBar(0,100);
timerBar.setOrientation(JProgressBar.VERTICAL);
timerBarLabel = new JLabel("Play");
timerBarLabel.setForeground(Color.white);
progPanel.add(timerBarLabel);
progPanel.add(timerBar);

This is my code for my progress bar.

Was it helpful?

Solution

As noted the documentation for JProgressBar (I'm assuming you are using Java 6), you can use the getValue() method to retrieve the progress bar's current value from the BoundedRangeModel.

So,

int maximum = timerBar.getMaximum();
int value = timerBar.getValue(); // This will be the value from 0 to 100 inclusive
String text = String.format("%d/%d", value, maximum);

The above would result in text containing the string "x/y", where x is the current value of the JProgressBar and y is the maximum value of the same.

If you want to draw this inside the progress bar, you may be interested in setString(String s) and setStringPainted(boolean b),

timerBar.setStringPainted(true);
timerBar.setString(text);

And since the value of the progress bar will be changing, you will want to update the text each time the value changes.

OTHER TIPS

If I understand your question correctly, I would think something as simple this should do the job:

progressBar.setString("Text Here!");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top