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

时间:2014-04-25 17:16:32

标签: java swing jframe jpanel

我想将BreadPanel.java更改为MeatPanel.java

这是" main"的代码。类。

    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();
       }
   });
   }
}

以下是我想要为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);

    //

调用actionlistener时是否有更好的方法来更改这些面板?

由于

2 个答案:

答案 0 :(得分:2)

使用CardLayout并将JFrame添加到其中。根据事件,显示适当的框架。  请点击How to Use CardLayout

了解更多信息

答案 1 :(得分:2)

  

"调用actionlistener时是否有更好的方法来更改这些面板?"

是。您可以使用CardLayout来交换面板视图,这样您就不必继续删除和添加面板。点击How to Use CardLayout了解更多信息。另请参阅一个简单示例here

相关问题