我正在用Java Swing編寫Java程序。我有一個類,它是一個自定義JPanel(我的類擴展JPanel),它是一個登錄頁面。該面板包含一個名爲「Enter」的按鈕。當按下不同類別的按鈕時Java Swing更改面板
當我創建我的主要JFrame時,我在其中添加了登錄面板。當按下「Enter」按鈕時,我想要移除「登錄」面板並進入下一個面板。
那麼我怎樣才能讓我的框架瞭解當按下「輸入」從登錄面板按下(他們在不同的類),以便它進行到下一頁?
我正在用Java Swing編寫Java程序。我有一個類,它是一個自定義JPanel(我的類擴展JPanel),它是一個登錄頁面。該面板包含一個名爲「Enter」的按鈕。當按下不同類別的按鈕時Java Swing更改面板
當我創建我的主要JFrame時,我在其中添加了登錄面板。當按下「Enter」按鈕時,我想要移除「登錄」面板並進入下一個面板。
那麼我怎樣才能讓我的框架瞭解當按下「輸入」從登錄面板按下(他們在不同的類),以便它進行到下一頁?
爲了能夠切換beetween JPanels將它們用CardLayout:
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
您應該添加ActonListener的 「確定」 按鈕:
JButton enterButton = ...
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout)// your reference to the CardLayout here eg. yourJFrame.getContentPane().getLayout();
cl.show(cards, "The name of panel to show, you gave it with the add operation on cardLayout eg. BUTTONPANEL OR TEXTPANEL");
}
});
從概念上講,「行爲」管理是「面板」的責任,導航是「容器」的責任,因此「面板」需要在工作完成時讓「容器」知道,「容器」應該決定如何處理。這保持了對單一責任範式的鬆散耦合和堅持。我只提到它,因爲我不知道'enterButton'在哪個層次上;) – MadProgrammer
是的,但試着用簡單的回答來解釋它:如何在按鈕點擊時切換面板?做我的客人,改進答案:) –
[我不需要](http://stackoverflow.com/questions/26517856/java-and-gui-where-do-actionlisteners-belong-according-to-mvc模式/ 26518274#26518274)或至少[不再](http://stackoverflow.com/questions/27663306/open-a-jpanel-after-pressing-a-button-in-a-jframe/27663749#27663749 ):P – MadProgrammer
如何?讓我數一下......認真地說,有這麼多。你可以讓父類向'LogIn'面板註冊'ActionListener',但更強大的解決方案是使用某種MVC [例如](http://stackoverflow.com/questions/26517856/java -and-gui-where-do-actionlisteners-belong -with-to-mvc-pattern/26518274#26518274)and [example](http://stackoverflow.com/questions/27663306/open-a-jpanel-after-按一個按鈕在一個jframe/27663749#27663749) – MadProgrammer
你也應該成爲農場與[觀察者模式](http://www.oodesign.com/observer-pattern.html) – MadProgrammer
謝謝你,我沒有意識到這一點。 – user3309479