how to add and remove components(JButons , JTextField etc) at runtime in a Swing program (Java ) , without using NetBeans ? which Layout should I use ?
I want the user to enter Username & Password and , when he clicks on Submit button , the new screen with new components(JButtons , JTextField etc) should appear , I am unable to achieve the transition at runtime.
how to add and remove components(JButons , JTextField etc) at runtime in a Swing
Share
You want to use two different panels to achieve this result. It’s not a good idea to use the same panel and remove all of the first components and add all of the second ones.
Make a LoginPanel class which lays out the username and password fields, labels, and submit button. Then, when the submit button is pressed, after the login is authenticated, hide the login panel and display a new panel with the layout you want for the next screen.
This sort of approach makes it much easier to maintain the two panels, and clearly separates their layouts and functionality from each other.
You can center this new frame over the existing panel using this code:
public static void centerFrameOverComponent(JFrame frame, JComponent component) { Window parent = SwingUtilities.getWindowAncestor(component); Rectangle frameRect = frame.getBounds(); Rectangle parentRect = parent.getBounds(); int x = (int) (parentRect.getCenterX() - frameRect.getWidth() / 2); int y = (int) (parentRect.getCenterY() - frameRect.getHeight() / 2); frame.setLocation(x, y); }