I've been learning quite a lot in Java recently but something has been really bugging me. I learned / was taught how to use ActionListeners when the program involves a constuctor, for example,
public class test extends JFrame implements ActionListener {
JButton button;
public test
{
setLayout(null);
setSize(1920,1080);
setTitle("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("");
button.setBounds(x,x,x,x);
button.AddActionListener(this); //What can replace the this parameter here.
button.setVisible(true);
add(button);
}
public static void main(String[] args) {
test testprogram = new test();
test.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent clickevent) {
if (clickevent.GetSource() == button) {
//DoSomething
}
}
It can be anything which implements ActionListener
.
You might want to consider not making your JFrame
implement ActionListener
: this means that
actionPerformed
; but you probably don't want other classes to call that directly.The alternative is to create a button
-specific action listener:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent clickevent) {
// Don't need to check if it is from button, nothing else
// could have created the event.
}
});
and remove implements ActionListener
from the test
class.