Here's how to change card layouts from a menu item. I asked how to do it earlier but no luck. I have figured out the answer so here's what it does; 1. Builds your main frame when running the java file. Then in the menu bar it allows you to switch JPanels (For this example welcome is a different public class inside of a package.) 2. Now you can build as many public classes as you want and still be able to go to that 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);
}
}
Two things I see going on.
SuggestedQuesion_2declared globally then you create a whole new one in you method.JPanel SuggestedQuestion_2 = new JPanel();CardLayoutfor yourWelcome-Welcome.setLayout(new CardLayout(0, 0));, but not for youSuggestedQuestion_2. Yet you're trying to accessSuggestedQuestions'sCardLayoutYou should learn how to post an SSCCE So it is easier for us to see the problem. Also, in trying to recreate the problem into a smaller, runnable version you sometimes figure out the solution yourself.
And please follow Java naming convention using lowercase letters first letter of reference variable