2016-05-07 77 views
1

我有兩個JPanels,我想在用戶點擊它們時切換。如何在CardLayout中的JPanel之間切換?

所以我創建了一個Window其中JFrame。然後我創建一個名爲cardsJPanel,並將其佈局設置爲CardLayout。然後再創建兩個JPanel - 這些是我想要切換的面板 - 並將它們添加到cards。我添加了mouseClicked事件監聽器,並添加了cardLayout.next(cards),因此交換機將會發生。它不起作用。

這裏是我的代碼:

public class Window { 
    private JFrame frame; 
    private JPanel cards; 
    private JPanel panel1; 
    private JPanel panel2; 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        Window window = new Window(); 
        window.frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 
    public Window() { 
     initialize(); 
    } 
    private void initialize() { 
     frame = new JFrame(); 
     frame.setBounds(100, 100, 790, 483); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     cards = new JPanel(); 
     cards.setLayout(new CardLayout()); 
     panel1 = new JPanel(); 
     panel1.setBackground(Color.BLACK); 
     panel1.addMouseListener(new MouseAdapter() { 
      public void mouseClicked(MouseEvent e){ 
       java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep 
       CardLayout cl = (CardLayout) cards.getLayout(); 
       cl.next(cards); 
      } 
     }); 

     panel2 = new JPanel(); 
     panel2.setBackground(Color.WHITE); 
     panel1.addMouseListener(new MouseAdapter() { 
      public void mouseClicked(MouseEvent e){ 
       CardLayout cl = (CardLayout) cards.getLayout(); 
       cl.next(cards); 
      } 
     }); 

     cards.add(panel1, "panel1"); 
     cards.add(panel2, "panel2"); 

     frame.getContentPane().add(cards); 
    } 

} 

爲什麼它不工作?

回答

4

您已將2 MouseListeners添加到同一個面板,可有效地取消撥打CardLayout.next的電話。更換的

panel1.addMouseListener(new MouseAdapter() { 

一個與

panel2.addMouseListener(new MouseAdapter() { 
+0

謝謝。多煩人的錯誤。我想我並沒有很好地說明我的變量。 –