我在主类中为我的程序创建了一个框架(大型机),我想在其中添加和删除面板,以便在我的程序的不同屏幕之间切换。我的程序的第一个屏幕是登录面板,它有一个开始按钮。当我按下开始按钮时,我想切换到菜单框架。
removeAll 方法似乎工作正常,因为登录面板消失了,但是当我使用添加、验证和重绘方法时,它的位置什么也没有出现。我试图在 Action 监听器(即 mainframe.add(menu))中明确引用大型机,但它无法识别该对象。
提前致谢!
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);
}
}
这是我的登录面板类:
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) {
}});
}
最佳答案
I want to add and remove panels from in order switch between different screens of my program
听起来你应该使用 Card Layout .
关于java - 从 actionlistener 访问在 main 中创建的 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8215459/