以下是如何从菜单项更改卡片布局。我问过如何提前做但没有运气。我已经找到了答案,所以这就是它的作用; 1.运行java文件时构建主框架。然后在菜单栏中,它允许您切换JPanels(对于此示例,welcome是一个包内的不同公共类。)2。现在,您可以根据需要构建任意数量的公共类,并且仍然可以转到该JPanel。
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class ArmyQuestions {
CardLayout cards;
JPanel cardPanel;
public static void main(String[] args) throws IOException {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new ArmyQuestions();
}
});
}
public ArmyQuestions()
{
JFrame mainFrame = new JFrame();
//make sure the program exits when the frame closes
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Army Questions");
mainFrame.setSize(797,510);
//This will center the JFrame in the middle of the screen
mainFrame.setLocationRelativeTo(null);
mainFrame.getContentPane().setLayout(new BorderLayout());
//Adds a menu bar
JMenuBar menuBar = new JMenuBar();
mainFrame.getContentPane().add(menuBar, BorderLayout.NORTH);
//Adds a menu option
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
//Adds an item to the menu option
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
mntmNew.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
cards.show(cardPanel, "Welcome");
}
});
//Adds cardpanel to getContentPane
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
mainFrame.getContentPane().add(cardPanel,BorderLayout.CENTER);
//Adds a JPanel to your cardpanel
Welcome welcome = new Welcome();
cardPanel.add(welcome, "Welcome");
mainFrame.setVisible(true);
}
}
答案 0 :(得分:2)
我看到的两件事情。
SuggestedQuesion_2
,然后在您的方法中创建一个全新的JPanel SuggestedQuestion_2 = new JPanel();
。 CardLayout
Welcome
- Welcome.setLayout(new CardLayout(0, 0));
的{{1}},但不是SuggestedQuestion_2
。但您正在尝试访问SuggestedQuestions
的{{1}} 您应该了解如何发布SSCCE因此,我们更容易看到问题。此外,在尝试将问题重新创建为较小的可运行版本时,您有时会自己找出解决方案。
请使用小写字母引用变量的第一个字母
遵循Java命名约定