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.
you could create a new class for exsample MyFrame thath extends JFrame, that rapresetns your new windows, in the constructor of that class you have to add at the contentpanel your all contolr....
in this way you can add a jbutton to your JFrame.
class MyFrame extends JFrame{
private JButton jb= new JButton("hello");
public MyFrame(){
setSize(new Dimension(300,180)); //set the MyFrame size
getContentPane().add(jb); //add your Component at ContentPane
}
}
after the login you could show your new frame in this way:
new MyFrame().setVisible(true);
One approach would be to use CardLayout
. Your login button handler would check the credentials and use show()
to reveal the second pane.
Addendum: For security, consider using JPasswordField
for the password; for convenience, consdier setLocationRelativeTo()
for positioning the frame.
Another approach is to call setVisible(false)
on the specific component when you wish to hide it.
In cases where I have wanted to add/remove an entire sub panel, I have used the following:
panel.remove(subPanel);
panel.revalidate();
panel.repaint();
You want to call the last two methods whenever you add/remove components.
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); }