Reputation: 63
public class Main {
private JLabel lb = new JLabel();
private JButton btn = new JButton();
public class events extends JFrame{
public events(){
setLayout(new FlowLayout());
btn = new JButton("Click for text");
lb = new JLabel();
add(btn);
add(lb);
event e = new event();
btn.addActionListener(e);
}
public static stConst() {
}
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e) {
lb.setText("Now there is text here.");
}
}
public static void main(String[] args) {
events gui = new events();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 300);
gui.setVisible(true);
}
}
Ok so before you go yelling at me for my naming conventions let me say I know how bad my variable names are. I have been trying to figure out java.swing event handling and I finally found an example program that i thought might work but then it gave me the error "non-static variable cannot be referenced from static context". It give me the error on the line at the bottom where I call the constructor so I think the error has something to do with the "this" object used in the constructor or maybe for some reason it's not letting me call my non-static constructor from inside my static main function. How do I fix this?
Upvotes: 2
Views: 61
Reputation: 3894
As events is Non static inner class, it must need a reference of parent class to be initialized.
Option 1:
You can simply call the inner class constructor using below statement in static method:
events gui = new Main().new events();
Option 2:
Create a non static function (like init) and then create instance of events from that function. From static function create an instance of parent class and then call this non static function:
public static void main(String[] args) {
Main main = new Main();
main.init();
}
public void init() {
events gui = new events();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 300);
gui.setVisible(true);
}
Output:
Upvotes: 1
Reputation: 311393
Your inner classes, event
and events
aren't static
- they belong to a specific instance of your Main
class (or, in other words, each instance has it's own inner class). The main
method is static
, though, so you cannot refer to instance members (even if they are classes!) from it.
Changing the inner classes, along with the data members of Main
they rely on, to static
should solve the issue.
Upvotes: 1