您创建了一个使用CardLayout和卡片的JPanel,但是没有添加任何内容,因此它当然不会显示自身,也不会显示卡片。解决方案:将此JPanel添加到您的GUI。
所以代替:
main.setContentPane(welcomePanel());
做:
main.setContentPane(cards);
问题编号2:
将字符串用作键的类型时,请使用字符串常量。请注意,您因此将一个JPanel添加到卡JPanel中:
cards.add(home, "Home");
但是,然后尝试像这样显示它:
cl.show(cards, "home");
但是“家”与“家”不同。
而是声明一个常量HOME:
public static final String HOME = "home";
并使用相同的常量添加并显示JPanel。
举一个简单的例子:
import java.awt.CardLayout;import java.awt.event.ActionEvent;import javax.swing.*;public class MainGui2 extends JPanel { private CardLayout cardLayout = new CardLayout(); private WelcomePanel welcomePanel = new WelcomePanel(this); private HomePanel homePanel = new HomePanel(); public MainGui2() { setLayout(cardLayout); add(welcomePanel, WelcomePanel.NAME); add(homePanel, HomePanel.NAME); } public void showCard(String name) { cardLayout.show(this, name); } private static void createAndShowGui() { MainGui2 mainPanel = new MainGui2(); Jframe frame = new Jframe("MainGui2"); frame.setDefaultCloseOperation(Jframe.DISPOSE_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); }}class WelcomePanel extends JPanel { public static final String NAME = "welcome panel"; private MainGui2 mainGui2; public WelcomePanel(final MainGui2 mainGui2) { this.mainGui2 = mainGui2; add(new JLabel(NAME)); add(new JButton(new AbstractAction("Logon") { @Override public void actionPerformed(ActionEvent e) { mainGui2.showCard(HomePanel.NAME); } })); }}class HomePanel extends JPanel { public static final String NAME = "home panel"; public HomePanel() { add(new JLabel(NAME)); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)