swing: making a JProgressBar with a label superimposed on it?
I would like to use a JProgressBar
and augment it to print its current value as well as the graphical bar.
I'm guessing the best way to do this is to override paintComponent:
@Override protected void paintComponent(Graphics g) {
// Let component paint first
开发者_StackOverflow super.paintComponent(g);
// paint my contents next....
}
but I am not sure... any advice?
I would suggest you to use its own API:
public void setStringPainted(boolean b)
Sets the value of the stringPainted property, which determines whether the progress bar should render a progress string. The default is false, meaning no string is painted. Some look and feels might not support progress strings or might support them only when the progress bar is in determinate mode.
and
public void setString(String s)
Sets the value of the progress string. By default, this string is null, implying the built-in behavior of using a simple percent string. If you have provided a custom progress string and want to revert to the built-in behavior, set the string back to null. The progress string is painted only if the isStringPainted method returns true.
Reference is always a good thing. :)
Mind that to enable editing the value during its run you should consider having a ChangeListener
attached to the progress bar.
Working solution based on Jack's answer:
final JProgressBar pbar = ...
pbar.setStringPainted(true);
final NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(true);
pbar.setString(nf.format(pbar.getValue()));
pbar.addChangeListener(new ChangeListener()
{
@Override public void stateChanged(ChangeEvent event) {
pbar.setString(nf.format(pbar.getValue()));
}
});
精彩评论