package Application;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Application1 extends JFrame implements ActionListener
{
JButton b1;
Application1(){
setSize(700,600);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void labels(){
JLabel line = new JLabel("HELLO!");
add(line);
}
public void buttons(){
b1 = new JButton("Click To Win");
add(b1);
b1.addActionListener(new Application1());
}
public void end() {
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JLabel b2 = new JLabel(" System Hacked \n You Lost!");
}
public static void main(String[] args) {
Application1 app1 = new Application1();
app1.labels();
app1.buttons();
app1.end();
}
}
Why doesnt this work? pls see
Resolved
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Thomas
26 August 2023, 14:59
0
Harshit GargExpert
26 August 2023, 15:53
ok but you have changed the code a lot...
can you pls tell where had mistaken?
0
Thomas
26 August 2023, 15:57solution
I mentioned it in the code. The biggest problem was to create a new action listener object for the button while it ought to be this. The rest you should be able to find yourself.
0
Harshit GargExpert
26 August 2023, 16:03
Thanks! can you please explain how why..?
0
Thomas
26 August 2023, 16:26
when you implement the ActionListener interface then the Application1 class not only serves as your base class to hold necessary data (button, label) but also as JFrame and the listener. Means the listener can directly access the label and button.
But when you create a new Application1 object and pass it as listener to the button, then this new object also has a new set of aggregated objects (button and label) that it would use (instead of the ones you'd wished/ expected it to use).
That's why you usually use lambdas for small and easy listeners (for buttons) and if it gets more complicated you use dedicated classes (inner or fully fledged ones).
The approach to implement the listener interface is also best used for very small and simple listeners usage.
0