i want my progressbar at the center of the sreen. i already tried...

setLocationRelativeTo(null);

but when i run the program it didnt work. somehow it is not in the middle of the screen. Please help me. See image.

enter image description here

HERE ARE MY CODES

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

The GridBagConstraints

Anchor is Center, Grid Height 1, Grid Width 1, Grid X -1, Grid Y - 1

有帮助吗?

解决方案

You need to create GridBagConstraints and define anchor (among others like x_weight) to center in GridBagLayout

Then add the component to the layout like this

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

//set the constraints properties

layout.addLayoutComponent(JProgressBar, cons);

then

setLayout(layout)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top