如何在java中居中位置进度条

时间:2014-01-18 13:36:05

标签: java swing center layout-manager jprogressbar

我希望我的进度条位于屏幕中心。我已经尝试过......

setLocationRelativeTo(null);

但是当我运行程序时它没有用。不知何故,它不在屏幕中间。请帮我。见图。

enter image description here

这是我的代码

public class progressbar extends JFrame {
    private JProgressBar jp;
    private Timer t;
    int i = 0;

public progressbar() {

    setTitle("Loading...");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().setLayout(new GridBagLayout());
    setLocationRelativeTo(null);
    setUndecorated(true);
    setVisible(true);
    jp = new JProgressBar();
    // Paint the percent complete on progress bar
    jp.setStringPainted(true);
    jp.setPreferredSize(new Dimension(500, 30));
    jp.setMinimum(0);
    jp.setMaximum(1000);
    getContentPane().add(jp);
    pack();
    // Create a timer that executes for every 2 millisec
    t = new Timer(2, new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            jp.setValue(i++);
            if (i == 1000) {
                t.stop();
                setVisible(false);
                loginInterface l = new loginInterface();
                l.txtUser.requestFocus();
            }
        }
    });
    // Start the timer
    t.start();
}

GridBagConstraints

锚点是中心,网格高度1,网格宽度1,网格X -1,网格Y - 1

1 个答案:

答案 0 :(得分:1)

您需要创建GridBagConstraints并定义锚点(其中包括x_weight)以GridBagLayout为中心

然后将组件添加到布局中,如下所示

    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints cons = new GridBagConstraints();

//set the constraints properties

layout.addLayoutComponent(JProgressBar, cons);

然后

setLayout(layout)