我正在用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