0

I want to change BreadPanel.java to MeatPanel.java.

Here is my code for the "main" class.

    public class FinalProject {
    static JFrame frame; // How do I call this in another class

    // Get colors for example
    private static final Color GREEN = new Color(84, 204, 126);
    private static final Color WHITE = new Color(255, 255, 255);
    private static final Color MENUGREEN = new Color(161, 227, 141);

    // Create a method that creates the UI
    static void createAndShowGui() {
    frame = new JFrame("Subway Menu");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(new NavPanel(GREEN, 800, 60), BorderLayout.NORTH);
    frame.getContentPane().add(new QueuePanel(MENUGREEN, 200, 440), BorderLayout.EAST);

    // The panel I want to change on click
    frame.getContentPane().add(new BreadPanel(WHITE, 600, 440), BorderLayout.CENTER);


    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);
   }

   // Main
   public static void main(String[] args) {
   SwingUtilities.invokeLater(new Runnable() {
       public void run() {
           createAndShowGui();
       }
   });
   }
}

Here is my code for the panel that I want to change out for BreadPanel.

    class MeatPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private static final float FONT_POINTS = 16f;
    private int prefW;
    private int prefH;

    public JButton m1, m2, m3, m4, m5, m6, m7, m8, m9, m10;
    private JLabel calories, blank, choice;

        public MeatPanel(Color color, int prefW, int prefH) 
    {

    // Here is where I want to call it

        frame.getContentPane().remove(new BreadPanel(color, 600, 440),     BorderLayout.CENTER);
        frame.getContentPane().add(new MeatPanel(color, 600, 440), BorderLayout.CENTER);

    //

Is there a better way to change these panels when an actionlistener is called?

Thanks

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Michael
  • 9,639
  • 3
  • 64
  • 69

2 Answers2

2

Use CardLayout and add both the JFrames to it. Based on the event, show appropriate frame. See more at How to Use CardLayout

Mubin
  • 4,192
  • 3
  • 26
  • 45
2

"Is there a better way to change these panels when an actionlistener is called?"

Yes. You can use a CardLayout that will let you swap panel views, so you won't have to keep removing and adding panels. See more at How to Use CardLayout. Also see a simple example here

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720