重复单击时,JMenuItem ActionListener会触发多个ActionEvent

时间:2014-04-14 06:01:55

标签: java swing jmenuitem actionevent

我正在使用带有mysql的JTable。在GUI中我有一些jmenus和jbuttons。我有一个带有ActionListener的JMenuItem:

public JMenuBar createMenuBar() {

    bar = new JMenuBar();       
    bar.add(fileMenu);

    add = new JMenuItem("Add Customer");
    fileMenu.add(add);
    add.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (table_HALE_ACCOUNTS == null)
                JOptionPane.showMessageDialog(contentPane, "First Load from Database"); 
            else {
                displayAccountsTable();
                addCustomerContainer();
                contentPane.revalidate();
                contentPane.repaint();
                }   
            }
        });
return bar;
}   

private void displayAccountsTable() {
    if (contentPane != null) {
        contentPane.removeAll();
        contentPane.revalidate();
        contentPane.repaint();
    }
    contentPane = getContentPane();
    contentPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    contentPane.setLayout(new GridBagLayout());
    c = new GridBagConstraints();

    c.fill = GridBagConstraints.BOTH;
    c.anchor = GridBagConstraints.CENTER;
    c.weightx = 0.5;
    c.weighty = 1.0;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;

    contentPane.add(new JScrollPane(table_HALE_ACCOUNTS), c);
    contentPane.revalidate();
    contentPane.repaint();
}


    public void addCustomerContainer() {
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.LINE_END;
    c.weightx = .25;
    c.weighty = 0;
    c.gridx = 1;
    c.gridy = 5;
    c.gridwidth = 1;
    contentPane.add(button_ADD_CUSTOMER, c);

    button_ADD_CUSTOMER.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            String stringDeposit = textField_DEPOSIT.getText();
            double doubleDeposit = Double.parseDouble(stringDeposit);
            String stringDate = textField_DATE.getText().replaceAll("\\s", "");
            int intDate = Integer.parseInt(stringDate);

            try {   
                myAccountTableModel.insertRow(textField_NAME.getText(), textField_CUSTOMER_ID.getText(), doubleDeposit, intDate);
                textFieldSetText();  
                contentPane.revalidate();
                contentPane.repaint();
            } catch (SQLException e1) {
                e1.printStackTrace();
                }               
            }
        }); 
    }

代码可以正常显示JTable并在我的表模型中插入一行。问题是当我多次单击JMenuItem“添加客户”时。执行此操作并按下JButton“button_ADD_CUSTOMER”后,每次单击JMenuItem执行ActionEvent插入操作。只需单击一次,JButton就会插入多行而不是一行。

JMenuItem的ActionEvent中的某些内容似乎只需单击一下JButton即可递增和释放。

我希望阻止来自JMenuItem点击的多个插入,但是每次我想执行单个插入时都保留点击JButton的能力。

感谢您的时间。

0 个答案:

没有答案