Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p>Well i don't see any problem when you know that <code>evt.getSource()</code> return the source Component of the <code>ActionEvent</code>. </p></li> <li><p>To register an action listener to a component like <code>JButton</code>, we usually do this:</p> <pre><code>jButton.addActionListener(anActionListener); </code></pre> <p>For your context you can pass <code>ActionListener</code> using the help of <code>this</code>. </p></li> <li><p>Do not implement <code>ActionListener</code> interface to some class which doesn't listen to such Event or have them. If required declare a new class by implementing it and use instance of that class to register the listener.</p> <pre><code> class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { // press the button } } MyActionListener actionListener = new MyActionListener(); jButton1.addActionListener(actionListener); jButton2.addActionListener(actionListener); jButton3.addActionListener(actionListener); </code></pre></li> </ol> <blockquote> <p>I'm trying to dynamically add buttons (JButtons), which changes names everytime.</p> </blockquote> <p>But you are probably having misconception about setting name with <code>new JButton("some text")</code>. This doesn't set name of the Button, rather it's text content. You need to use <code>button.setName("aName")</code> instead.</p> <p>However, You can always use the either of the <code>getName</code> or <code>getText</code> method to identify your specific button.</p> <pre><code>public void actionPerformed(ActionEvent e) { // press the button JButton button = (JButton)e.getSource(); Syestem.out.println(button.getName()); // get the name System.out.println(button.getText()) // get the text content if(button.getText().equals("clearBtn")) // clear things for me } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload