2015-11-09 105 views
-1

這是我的LoginGUI類,我想從這個GUI類移動到另一個「StudentGUI」類。它似乎很簡單,但我想不出如何從一個GUI類傳遞到另一個GUI類?

JButton btnNewButton_1 = new JButton("Log In"); 
    btnNewButton_1.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent e) { 

      if(Username.equals(textField1.getText())){ 

        if(Password.equals(textField2.getText())){ 
         // close(LoginGUI); 
         // run(StudentGUI); 

        **Missing function** 

         msg = "Loged in!"; 
        }else{ 
         msg = "Login Denied"; 
        } 
       }else{ 
        msg = "Login Denied"; 
       } 
       JOptionPane.showMessageDialog(null,msg);      
      } 




     }); 
    btnNewButton_1.setBounds(157, 230, 89, 23); 
    frame.getContentPane().add(btnNewButton_1); 
} 

}

+1

你需要有其他用戶的一個實例。沒有任何其他類的代碼,它不可能幫助更多。除此之外 - 嘗試抓取一本java基礎書籍,並在開始使用UI編程之前瞭解面向對象的編程 –

+0

我向您推薦使用[CardLayout](https://docs.oracle.com/javase/tutorial/uiswing/佈局/ card.html)。使用多個JFrames是不好的做法。 – Jonah

+1

在您的具體情況下,您不需要。允許UI簡單地充當從用戶收集信息的機制,允許另一個類(控制器)確定當用戶試圖驗證他們的憑證時應該發生什麼,以及用於執行實際驗證的模型。驗證後,一個單獨的控制器會對導航進行確定。有關詳細信息,請參見[Model-View-Controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) – MadProgrammer

回答

1

如果你想在多個視圖之間切換,使用CardLayout這裏有一個簡單的例子

package main.frames; 

import javax.swing.*; 
import java.awt.*; 

public class MainFrame extends JFrame 
{ 
static JPanel homeContainer; 
static JPanel homePanel; 
static JPanel otherPanel; 
static CardLayout cl; 

public MainFrame() 
{ 
    JButton showOtherPanelBtn = new JButton("Show Other Panel"); 
    JButton backToHomeBtn = new JButton("Show Home Panel"); 

    cl = new CardLayout(5, 5); 
    homeContainer = new JPanel(cl); 
    homeContainer.setBackground(Color.black); 

    homePanel = new JPanel(); 
    homePanel.setBackground(Color.blue); 
    homePanel.add(showOtherPanelBtn); 

    homeContainer.add(homePanel, "Home"); 

    otherPanel = new JPanel(); 
    otherPanel.setBackground(Color.green); 
    otherPanel.add(backToHomeBtn); 

    homeContainer.add(otherPanel, "Other Panel"); 

    showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel")); 
    backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home")); 

    add(homeContainer); 
    cl.show(homeContainer, "Home"); 
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
    setLocationRelativeTo(null); 
    setExtendedState(JFrame.MAXIMIZED_BOTH); 
    setTitle("CardLayout Example"); 
    pack(); 
    setVisible(true); 
} 

public static void main(String[] args) 
{ 
    SwingUtilities.invokeLater(MainFrame::new); 
} 
} 
相關問題