2011-11-21 27 views
1

我在主類中爲我的程序創建了一個框架(大型機),我想添加和刪除面板以便在我的程序的不同屏幕之間切換。我的程序的第一個屏幕是具有開始按鈕的登錄面板。當我按下開始按鈕時,我想切換到菜單框架。從actionlistener訪問主要創建的JFrame

removeAll方法似乎工作正常,因爲登錄面板消失了,但是當我使用add,validate和repaint方法時,在它的位置沒有任何東西出現。我試圖明確指出actionlistener中的大型機(即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) { 

     }}); 

} 
+1

你可以請你的代碼在http://sscce.org/表格 – mKorbel

+0

我的隨機猜測,如果你要添加到你已經刪除的嵌套面板。那個或者你添加到哪個面板的其他錯誤。 –

+0

在相當基礎的層面上,我想知道爲什麼在我的主類中JFrame公開靜態不能在另一個類中解決:S - 任何想法? @mKorbel – user1058210

回答

4

我想添加和刪除面板在不同之間順序切換我的程序屏幕

聽起來像你應該使用Card Layout

+0

我解決了它!我所做的是引用框架製作的類:Main.mainframe。然後在actionlistener部分中,我創建了一個容器,並將其用作引用它的更方便的方法,如下所示: Container content = Main.mainframe.getContent(); content.removeAll();等等 – user1058210

1

定義mainframe爲一類領域:

private JFrame mainframe;