简体   繁体   English

从另一个类调用JFrame以更改JPanel

[英]Call JFrame from another class to change JPanel

I want to change BreadPanel.java to MeatPanel.java . 我想将BreadPanel.java更改为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. 这是我要更改为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 谢谢

Use CardLayout and add both the JFrame s to it. 使用CardLayout并将两个JFrame添加到其中。 Based on the event, show appropriate frame. 根据事件,显示适当的框架。 See more at How to Use CardLayout 在“ 如何使用CardLayout”中查看更多信息

"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. 您可以使用CardLayout来交换面板视图,因此您不必继续删除和添加面板。 See more at How to Use CardLayout . 有关更多信息,请参见如何使用CardLayout Also see a simple example here 在这里也可以看到一个简单的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM