Java中的开关卡布局
下面介绍如何从菜单项更改卡片布局。我问怎么早点做,但运气不好。我已经找到了答案,下面是它的作用;1.运行java文件时构建主框架。然后在菜单栏中,它允许您切换JPanels(例如,welcome是一个包中的另一个公共类)。现在,您可以构建任意数量的公共类,并且仍然可以访问该JPanelJava中的开关卡布局,java,swing,cardlayout,Java,Swing,Cardlayout,下面介绍如何从菜单项更改卡片布局。我问怎么早点做,但运气不好。我已经找到了答案,下面是它的作用;1.运行java文件时构建主框架。然后在菜单栏中,它允许您切换JPanels(例如,welcome是一个包中的另一个公共类)。现在,您可以构建任意数量的公共类,并且仍然可以访问该JPanel import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.EventQueue; import java.awt.even
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);
}
}
我看到了两件事
SuggestedQuesion_2
,然后在方法中创建了一个全新的<代码>JPanel SuggestedQuestion_2=新JPanel()代码>cardplayout
用于您的Welcome
-Welcome.setLayout(新的cardplayout(0,0))代码>,但不适用于您建议的问题2
。但您正在尝试访问建议的问题
的卡片布局
请遵循Java命名约定,使用小写字母第一个参考字母变量请编辑您的代码,删除与问题无关的任何代码。另外,您遇到的确切问题是什么?我已经回答了自己的问题并发布了答案。我建议您学习手工编写swing程序。在以后使用GUI构建器工具进行创建时,您将学到许多有助于您的东西。我不习惯使用GUI构建器,所以我很难尝试解决您的问题