0

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Rohan21
  • 353
  • 5
  • 9
  • 24
  • already solved the problem. i put the setLocationRelativeTo(null); below the pack(); and it solve my problem. – Rohan21 Jan 18 '14 at 14:50

1 Answers1

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)
Typo
  • 1,875
  • 1
  • 19
  • 32
  • i already have it. i forgot to post it the Anchor is Center, Grid Height 1, Grid Width 1, Grid X -1, Grid Y - 1. – Rohan21 Jan 18 '14 at 13:45
  • You're setting the layout and then not adding the component to the layout as I explained. You need to create an object instead off passing a new one when you set the layout on the JFrame – Typo Jan 18 '14 at 13:56