简体   繁体   中英

Identifying which button was pressed

I'm trying to build a GUI which has a lot of buttons(JButton)/dropdown items (JMenuItem) and when each button containing letters is pressed the associated letter is being added to a label.

I'm having trouble identifying which button was pressed.Can you please give me a tip on how to do this?

Code:

 private void dodajCrko(java.awt.event.ActionEvent evt) {                           
    jlStatus.setText(jlStatus.getText() + evt.getSource()/* what to add here?*/);
}

I think you need this

((Button)actionEvent.getSource()).getLabel()

This will give you the label of the button clicked. You need to type cast the Source to Button like (Button)actionEvent.getSource()

Your code should be

private void dodajCrko(java.awt.event.ActionEvent evt) {                           
    jlStatus.setText(jlStatus.getText() + 
    ((Button)actionEvent.getSource()).getLabel());
}

As @Anto said, You should use actionEvent.getActionCommand() if you use any toggle buttons because the command string would identify the intended action.

I would use the getActionCommand() method:

private void dodajCrko(java.awt.event.ActionEvent evt) {                           
    jlStatus.setText(jlStatus.getText() + actionEvent.getActionCommand());
}

In my opinion i find this works better.

private JButton button1;

Then use this.

    button1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Button 1 was presseed");
        }
    });

Hope this helps, Luke.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM