将JProgressBar宽度设置为固定大小

时间:2014-09-02 22:21:09

标签: java swing jprogressbar

JProgressBar上有一个JToolBar。问题是JProgressBar占用了JToolBar上的所有剩余空间,而不是固定宽度。

我尝试过使用:

Dimension prefSize = goButton.getPreferredSize();
prefSize.width = 100;//some width
progressBar.setPreferredSize(prefSize);
progressBar.setVisible(true);

没有成功。 JProgressBar继续占用所有剩余空间。

如何强制JProgressBar拥有固定宽度?

这是我的问题的一个小的可运行的例子:

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();

    }
}

1 个答案:

答案 0 :(得分:3)

JProgressBar添加到JPane并将JPane添加到JToolBar

很高兴它有所帮助:)