I've a JProgressBar on my JToolBar. The problem is that the JProgressBar is taking all the remaining space on the JToolBar instead of having a fixed width.
I've tried using:
Dimension prefSize = goButton.getPreferredSize();
prefSize.width = 100;//some width
progressBar.setPreferredSize(prefSize);
progressBar.setVisible(true);
To no success. The JProgressBar keeps taking all the remaining space.
How can I force the JProgressBar to have a fixed width?
Here is a small runnable example of my problem:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JToolBar;
public class SimpleToolbar extends JFrame {
class ToolBar extends JToolBar {
private final JLabel labelSomething;
private final JLabel labelAnything;
private final JButton goButton;
private final JButton cancelButton;
private final JButton pauseButton;
private final JProgressBar progressBar;
public ToolBar()
{
setBorder(BorderFactory.createEtchedBorder());
setFloatable(false);
goButton = new JButton("Go");
cancelButton = new JButton("Cancel");
pauseButton = new JButton("Pause");
labelAnything = new JLabel("Anything");
labelSomething = new JLabel("Something");
progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
Dimension prefSize = goButton.getPreferredSize();
prefSize.width = 100;//some width
progressBar.setPreferredSize(prefSize);
progressBar.setVisible(true);
add(goButton);
add(cancelButton);
add(pauseButton);
addSeparator();
add(labelAnything);
add(labelSomething);
addSeparator();
add(progressBar);
}
}
protected ToolBar toolBar;
public SimpleToolbar() {
super();
setSize(600, 350);
toolBar = new ToolBar();
getContentPane().add(toolBar, BorderLayout.NORTH);
setVisible(true);
}
public static void main(String[] a) {
new SimpleToolbar();
}
}
Add your JProgressBar to a JPane and add the JPane to the JToolBar
Glad it helped :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With