![](/img/trans.png)
[英]Implementing and calling JFrame/ActionListener class from main
[英]Accessing JFrame created in main from actionlistener
我已經在主類中為我的程序創建了一個框架(大型機),我想從中添加和刪除面板,以便在程序的不同屏幕之間切換。 我程序的第一個屏幕是具有啟動按鈕的登錄面板。 當我按下開始按鈕時,我想切換到菜單框架。
因為登錄面板消失了,所以removeAll方法似乎工作正常,但是當我使用add,validate和repaint方法時,什么都沒有出現。 我試圖顯式地引用動作偵聽器中的大型機(即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) {
}});
}
我想添加和刪除面板,以便在程序的不同屏幕之間切換
聽起來您應該使用Card Layout 。
將mainframe
定義為類字段:
private JFrame mainframe;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.