ClickMe2.java:21: non-static variable button1 cannot be referenced from a static context
button1 = new JButton("Click Me!");
^
ClickMe2.java:22: non-static variable cl cannot be referenced from a static context
button1.addActionListener(cl);
^
ClickMe2.java:22: non-static variable button1 cannot be referenced from a static context
button1.addActionListener(cl);
^
ClickMe2.java:23: non-static variable button1 cannot be referenced from a static context
panel1.add(button1);
^
4 errors
Code:
import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class ClickMe2 { public static void main(String [] args) { new ClickMe2(); } private JButton button1; public ClickMe2() { JFrame f=new JFrame(); f.setSize(200,100); f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); f.setTitle("I’m Listening"); ClickListener cl = new ClickListener(); JPanel panel1 = new JPanel(); button1 = new JButton("Click Me!"); button1.addActionListener(cl); panel1.add(button1); f.add(panel1); f.setVisible(true); } class ClickListener implements ActionListener { private int clickCount = 0; public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) { clickCount++; if (clickCount == 1) button1.setText("I’ve been clicked!"); else button1.setText("I’ve been clicked " + clickCount + " times!"); } } } }