Reputation: 1689
I've created a frame (mainframe) for my program in the main class which I want to add and remove panels from in order switch between different screens of my program. The first screen of my program is the login panel which has a start button. When I press the start button I want to switch to the menu frame.
The removeAll method seems to work fine since the login panel disappears, but nothing appears in its place when I use the add, validate and repaint methods. I have tried to refer explicitly to the mainframe in the actionlistener (i.e. mainframe.add(menu)) but it does not recognise the object.
Thanks in advance!
public class Main {
public static JFrame mainframe = new JFrame();
public static void main(String[] args) {
// Create mainframe to add and remove panels from
LoginPanel lp = new LoginPanel();
System.out.println("mainframe created!");
// Set size of mainframe
mainframe.setBounds(0, 0, 500, 500);
mainframe.add(lp);
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the new location of the mainframe
int w = mainframe.getSize().width;
int h = mainframe.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
// Move the mainframe
mainframe.setLocation(x, y);
mainframe.setVisible(true);
}
}
This is my login panel class:
public class LoginPanel extends JPanel {
private JTextField usernameField;
private JPasswordField passwordField;
private final Action action = new SwingAction();
/**
* Create the panel.
*/
public LoginPanel() {
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String (passwordField.getPassword());
Login login = new Login();
boolean Correct = login.isCorrect(username, password);
**if (Correct == true){
removeAll();
Menu menu = new Menu();
add(menu);
validate();
repaint();
setBounds(0, 0, 500, 500);
System.out.println("Attempted to start menu!");
}**
}
});
btnLogin.setAction(action);
btnLogin.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
}});
}
Upvotes: 1
Views: 2189
Reputation: 324108
I want to add and remove panels from in order switch between different screens of my program
Sounds like you should be using a Card Layout.
Upvotes: 4