2014-05-09 46 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

谢谢!那就是诀窍 –

相关问题