2014-05-09 107 views
0

我有下面的代碼,我試圖捕獲一個actionPerformed事件,但它永遠不會到達那裏。可能是什麼原因?actionPerformed在執行ActionListener時沒有觸發

public class NotePanel extends JPanel implements ActionListener { 

    /** 
    * 
    */ 
    private static final long serialVersionUID = 6562595937363664309L; 

    // hash table 
    private Hashtable<Integer, String> hash; 

    // comboboxes 
    JComboBox day, month, year; 

    // text area 
    JTextArea textArea; 

    public NotePanel(JTextArea textArea) { 
     hash = new Hashtable<Integer, String>(); 
     this.textArea = textArea; 
     addComponents(); 
    } 

    private void addComponents() { 
     setLayout(new GridLayout(2, 3)); 
     // add comboboxes 
     Integer[] dates = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; 
     day = new JComboBox(dates); 
     add(day); 
     Integer[] months = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; 
     month = new JComboBox(months); 
     add(month); 
     year = new JComboBox(); 
     year.setEditable(true); 
     add(year); 
     // add get and set buttons 
     JButton saveButton = new JButton("Save Memo"); 
     saveButton.setActionCommand("Save"); 
     JButton getButton = new JButton("Get Memo"); 
     getButton.setActionCommand("Get"); 
     add(saveButton); 
     add(getButton); 
    } 

    @Override 
    public void actionPerformed(ActionEvent evt) { 
     String cmd = evt.getActionCommand(); 
     Date date = new Date(getNumberFromCombo(day), getNumberFromCombo(month), getNumberFromCombo(year)); 
     int hashCode = date.hashCode(); 
     if (cmd.equals("Get")) { 
      if (hash.containsKey(hashCode)) { 
       textArea.setText(hash.get(date.hashCode())); 
      } else { 
       textArea.setText(""); 
      } 
     } else if (cmd.equals("Save")) { 
      hash.put(hashCode, textArea.getText()); 
     } 
    } 
} 

主要是很簡單的:

public static void main(String[] args){ 
    SwingUtilities.invokeLater(new Runnable(){   
     public void run(){ 
      createAndShowGUI(); 
     } 
    }); 
} 

private static void createAndShowGUI(){ 
    JFrame f = new JFrame("Maman 14 - Part 2"); 
    f.setResizable(false); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.setLayout(new GridLayout(2,1)); 
    // add text area 
    JTextArea textArea = new JTextArea(); 
    f.add(new NotePanel(textArea)); 
    f.add(textArea); 

    f.pack(); 
    f.setFocusable(true); 
    f.setVisible(true); 
} 

謝謝!

回答

2

你必須在按鈕addComponents註冊您的面板作爲一名聽衆:

saveButton.addActionListener(this); 
getButton.addActionListener(this); 
+0

謝謝!那就是訣竅 –

相關問題