I am learning Java. I am painstakingly learning the fundamentals of Java GUI. I made a "counter" program, which increments a variable by 1 every time you click a button.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class guitry implements ActionListener {
int counter = 0;
public guitry() {
JFrame frame = new JFrame("FrameDemo");
JPanel panel = new JPanel(new FlowLayout(1));
JLabel label = new JLabel("Clicked " + counter + " times");
JButton button = new JButton("CLick me");
panel.add(button);
panel.add(label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
System.out.println(panel.getLayout());
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
counter++;
System.out.println("clicked");
label.setText("Clicked " + counter + " times");
}
public static void main(String[] args) {
new guitry();
}
}
This code fails by "cannot find symbol" at line 27 in the action listener.
label.setText("Clicked " + counter + " times");
After stumbling upon an example that approaches the same task as me, it does this in the declarations so the action listener works:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class guitry implements ActionListener {
int counter = 0;
JLabel label; <----------------------------------------
public guitry() {
JFrame frame = new JFrame("FrameDemo");
JPanel panel = new JPanel(new FlowLayout(1));
label = new JLabel("Clicked " + counter + " times"); <----------------------
JButton button = new JButton("CLick me");
panel.add(button);
panel.add(label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
System.out.println(panel.getLayout());
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
counter++;
System.out.println("clicked");
label.setText("Clicked " + counter + " times");
}
public static void main(String[] args) {
new guitry();
}
}
I am absolutely gobsmacked as to why this works and am very lost. Thanks in advance for any answers.