How do you add an ActionListener onto a JButton in

2019-01-02 18:40发布

private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");

How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?

4条回答
伤终究还是伤i
2楼-- · 2019-01-02 18:56

idk if this works but I made the variable names

public abstract class beep implements ActionListener {
public static void main(String[] args) {
    JFrame f = new JFrame("beeper");
    JButton button = new JButton("Beep me");
    f.setVisible(true);
    f.setSize(300, 200);
    f.add(button);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //insert code here
        }
    } );

}

}

查看更多
不流泪的眼
3楼-- · 2019-01-02 19:03

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

查看更多
皆成旧梦
4楼-- · 2019-01-02 19:04

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

查看更多
查无此人
5楼-- · 2019-01-02 19:17

Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.

The short code snippet is:

jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
查看更多
登录 后发表回答