I am new to Java Programming. I would like to create JButton
inside the class and create ActionListener
in the main by passing button arguments. But it throws an error:
Cannot make a static reference to the non-static field newBtn
My code is as below.
import java.awt.event.*;
import javax.swing.*;
public class TestBtn {
TestBtn() {
}
public void myBtn(JButton mybtn){
JFrame f=new JFrame("My Example");
mybtn =new JButton("Click Here");
mybtn.setBounds(50,100,95,30);
f.add(mybtn);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
// My Main Program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TestBtnMain {
JButton newBtn;
public static void main(String[] args) {
TestBtn btn = new TestBtn();
btn.myBtn(newBtn);
newBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Success");
}
});
}
}