what's wrong in this code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class A implements ActionListener
{
public static void main(String args[])throws Exception
{
JFrame f=new JFrame("aravind");
JTextField t=new JTextField(30);
JButton b=new JButton("CLICK ME");
f.setSize(1000,1000);
f.setLayout(new FlowLayout());
f.add(t);
f.add(b);
b.addActionListener(this);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
System.out.println("CLICKED");
System.exit(0);
}
}
ERROR MESSAGE is:
C:\Documents and Settings\prabhu\Desktop>javac A.java
A.java:15: non-static variable this cannot be referenced from a static context
b.addActionListener(this);
^
1 error
Re: what's wrong in this code
Hey Arvind,
Usually in java the keyword "this" refers to the current object. And static means per class and not per object. The rule is that you can't access a non-static variable from a static method, which in your case is main method.
So instead of generating your GUI through main, you can build the same in some other method and call that method from main.
Here is the example,
Code java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class A implements ActionListener {
public static void main(String args[]) {
A a = new A();
a.click();
}
public void click() {
JFrame f = new JFrame("aravind");
JTextField t = new JTextField(30);
JButton b = new JButton("CLICK ME");
f.setSize(200, 200);
f.setLayout(new FlowLayout());
f.add(t);
f.add(b);
b.addActionListener(this);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("CLICKED");
System.exit(0);
}
}
I am not sure, why your main method was throwing the Exception, that wasn't needed; so I have removed it in this code above.
Hope that helps,
Goldest
Re: what's wrong in this code
Just in case if you are interested to do the things from main only, then you will have to change the implementation a bit.
You will need to use the static nested class inside your class. That nested class will have to implement the ActionListener interface. And you can pass the instance of that class to the addActionListener method.
Just like following,
Code java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class A {
public static void main(String args[]) {
JFrame f = new JFrame("aravind");
JTextField t = new JTextField(30);
JButton b = new JButton("CLICK ME");
f.setSize(200, 200);
f.setLayout(new FlowLayout());
f.add(t);
f.add(b);
b.addActionListener(new ClickTest());
f.setVisible(true);
}
static class ClickTest implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("CLICKED");
System.exit(0);
}
}
}
Hope that's clear to you...
Goldest