Hi everyone I'm starting to learn GUI on java and currently i'm using netbean IDE, i tried to create a jpanel and move it to the center of the screen but the problem is i can't move it to center automatically using a constructor using this code:
But it wokrs if im using a button with actionPerformed and it works. Here the code:
So why it cant automatically move to center of the screen using a constructor? Thank you very much
Beware of using NetBeans when you are learning Swing®; there is a risk it will start using the automated GUI builder and you will end up with incomprehensible code using the group layout.
Yes, you can set the location of a frame from the constructor, or from an initGUI() or similar method.
1: Don't subclass JFrame; most GUI components should not be subclassed.
2: In a simple GUI you can get away without any fields, making all your variables local variables.
As an alternative to setLocation() you can use setBounds(); you can also give all the added Components a preferred size and call pack() on the frame, probably best done after all other Components have been added, instead of setSize(). Be sure to use a layout, not null.
Don't call setLocation() from actionPerformed() because that may make your GUI move unpredictably and it will be difficult for users to use.
Set the location of a JFrame, not a panel. You can work out the size of the screen and the size of the panel and do a bit of arithmetic to move the frame to the appropriate location if you so wish. Remember the user will probably move the frame!
posted 1 month ago
Campbell Ritchie wrote:Welcome to the Ranch
Beware of using NetBeans when you are learning Swing®;. . . . Remember the user will probably move the frame!
Thank you very much for the information and the example, now I'm able to move it to the center also thanks for the tip i wont use netbeans GUI builder because somehow the generated code cant be edited and yeah it looks complicated XD. Thank you.
posted 1 month ago
That's a pleasure
Please don't quote the whole of a preceding post, but only the relevant parts. I have removed most of my post from the quote.