2014-04-25 78 views
0

我想將BreadPanel.java更改爲MeatPanel.java從另一個類調用JFrame來更改JPanel

這是我的「主」類代碼。

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

「當調用actionlistener時,有沒有更好的方法來改變這些面板?

是的。您可以使用CardLayout來交換面板視圖,因此您不必繼續移除和添加面板。請參閱How to Use CardLayout。另見一個簡單的例子here

+0

謝謝! CardLayout似乎是要走的路!我會很快標記你的答案。 – Michael