简体   繁体   English

是否有适当的方法在 Java Swing 上的单个 JFrame 上显示不同的组件集?

[英]Is there a proper way to show different set of components on a single JFrame on Java Swing?

I'm trying to figure out how to show a new set of components when I click a button.我试图弄清楚当我单击一个按钮时如何显示一组新的组件。 For example, when you click the login button it will log you in and show you the things you can do once logged in, but I want it to be on the same window(JFrame).例如,当您单击登录按钮时,它会登录并显示登录后您可以执行的操作,但我希望它在同一个窗口(JFrame)上。 All I can think of to do this is to put all the components in a single window then when I click a button I will hide the other components and show the others and vice versa.我能想到的就是将所有组件放在一个 window 中,然后当我单击一个按钮时,我将隐藏其他组件并显示其他组件,反之亦然。 Is there a proper way to do it?有正确的方法吗? or at least a better way?或者至少是更好的方法?

A good way is to use a JPanel to group screens and use CardLayout to switch between those panels.一个好方法是使用 JPanel 对屏幕进行分组并使用 CardLayout 在这些面板之间切换。

See https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html for introduction to using CardLayout and a working example.有关使用 CardLayout 和工作示例的介绍,请参阅https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html Each "screen" is represented by a JPanel containing desired components:每个“屏幕”都由一个包含所需组件的 JPanel 表示:

//Where instance variables are declared:
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM