Java: JProgressBar (or equivalent) in a JTabbedPane tab title
For earlier versions, you might try addTab()
with a suitable implementation of Icon
used to indicate progress.
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class JTabbedTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.setPreferredSize(new Dimension(400, 200));
createTab("Reds", Color.RED);
createTab("Greens", Color.GREEN);
createTab("Blues", Color.BLUE);
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
private void createTab(String name, Color color) {
ProgressIcon icon = new ProgressIcon(color);
jtp.addTab(name, icon, new ColorPanel(jtp, icon));
}
});
}
private static class ColorPanel extends JPanel implements ActionListener {
private static final Random rnd = new Random();
private final Timer timer = new Timer(1000, this);
private final JLabel label = new JLabel("Stackoverflow!");
private final JTabbedPane parent;
private final ProgressIcon icon;
private final int mask;
private int count;
public ColorPanel(JTabbedPane parent, ProgressIcon icon) {
super(true);
this.parent = parent;
this.icon = icon;
this.mask = icon.color.getRGB();
this.setBackground(icon.color);
label.setForeground(icon.color);
this.add(label);
timer.start();
}
public void actionPerformed(ActionEvent e) {
this.setBackground(new Color(rnd.nextInt() & mask));
this.icon.update(count += rnd.nextInt(8));
this.parent.repaint();
}
}
private static class ProgressIcon implements Icon {
private static final int H = 16;
private static final int W = 3 * H;
private Color color;
private int w;
public ProgressIcon(Color color) {
this.color = color;
}
public void update(int i) {
w = i % W;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect(x, y, w, H);
}
public int getIconWidth() {
return W;
}
public int getIconHeight() {
return H;
}
}
}
Enclose the JProgressbar in a JPanel and add that JPanel to the JTabbedPane.
Edit: From the JTabbedPane JavaDoc:
// In this case the custom component is responsible for rendering the title of the tab.
tabbedPane.addTab(null, myComponent);
tabbedPane.setTabComponentAt(0, new JLabel("Tab"));
So you could basically simply replace new JLabel("Tab")
by a reference to your JProgressbar (though this JProgressbar must not be added to the Tab itself).
However, I think this method doesn't exist prior to Java 1.6.