2012-06-21 243 views
2

我有下面的代碼創建一個簡單的窗口與兩個按鈕,這反過來又假設每個打開一個窗口 - 主窗口打開很好,但是當你點擊按鈕什麼都沒有發生...窗口沒有打開按鈕點擊

package presentation; 

import java.awt.Container; 
import java.awt.EventQueue; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class ShowInventory extends JFrame { 

    /** 
    * 
    */ 
    private static final long serialVersionUID = 7479750059244371227L; 
    private JPanel contentPane; 
    private JButton catBtn = new JButton ("Display inventory by category"); 
    private JButton allBtn = new JButton ("Display all inventory"); 


    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        ShowInventory frame = new ShowInventory(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
        System.out.println("Exception - Sorry"); 
       } 
      } 
     }); 
    } 

    /** 
    * Default - details to be added 
    */ 
    public ShowInventory() { // title bar name 

     // layout here 
     Container container = getContentPane(); 
     FlowLayout layout = new FlowLayout(); 
     container.setLayout(layout); 
     layout.setAlignment(FlowLayout.CENTER); 
     container.add(new JButton("Display inventory by category")); 
     container.add(new JButton("Display all inventory")); 


     catBtn.addActionListener (new ActionListener() { 
      public void actionPerformed (ActionEvent event) { 
       // controller code 
       ShowByCategory frame = new ShowByCategory(); 
       frame.setVisible(true); 
      } 
     }); 



     allBtn.addActionListener (new ActionListener() { 
      public void actionPerformed (ActionEvent event) { 
       // controller code 
       ShowAllInventory frame = new ShowAllInventory(); 
       frame.setVisible(true); 
      } 
     }); 

     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     pack(); 
     setVisible(true); 
    } 

} 
+0

請參閱[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/a/9554657/418556) –

回答

4

你可能需要更換這些線路(這創造全新的按鈕):

container.add(new JButton("Display inventory by category")); 
container.add(new JButton("Display all inventory")); 

本(使用你的類的按鈕,在其上再添加監聽器):

container.add(catBtn); 
container.add(allBtn); 
+0

,現在可以使用...只要它讓我接受,我會接受答案。你能告訴我爲什麼這有效嗎? – Expecto

+0

nm,你編輯它並做了!謝謝! – Expecto

+0

container.add中的按鈕(new JButton(「按類別顯示庫存」));'與catBtn無關,它是一個新對象。 – assylias