JFrame method prob

83 Views Asked by At

I am currently developing a small text-based game, and I keep getting an error... I don't know how to fix it, since its my first time using JFrame. The problem is, when I make the ButtonDemo method into ButtonDemo(), not public static void ButtonDemo(), there is a problem with the ButtonDemo(). However, if it is public static void ButtonDemo(), there would be an error on the jbtnW.addActionListener(this), saying that I cannot use the "this" because the ButtonDemo() is static.

package game;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import game.Storylines.*;

public class Frame implements ActionListener{
    VillageDrengr shops = new VillageDrengr();

    static JLabel jlab;

    static JFrame jfrm = new JFrame("A Game");

    public static void ButtonDemo() {
        jfrm.setLayout(new FlowLayout());
        jfrm.setSize(500, 350);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton jbtnW = new JButton("Equipment Shop");
        JButton jbtnP = new JButton("Potion Shop");

        jbtnW.addActionListener(this);
        jbtnP.addActionListener(this);

        jfrm.add(jbtnW);
        jfrm.add(jbtnP);

        jlab = new JLabel("Choose a Store.");
        jfrm.add(jlab);

        jfrm.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("Equipment Shop")) 
            jlab.setText("You went in to the Equipment Shop.");
        else
            jlab.setText("You went in to the Potion Shop.");
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ButtonDemo();
            }
        });
    }

}
1

There are 1 best solutions below

0
On

You're getting an error

non-static variable this cannot be referenced from a non-static context`.

What's happening is that this is referencing the ActionListener which isn't static.

A simple fix would be to make the ButtonDemo method non-static, and call the method from main like this

        public void ButtonDemo() {
        ....

        public void run() {
           new Frame().ButtonDemo();
        }

You instantiate the Frame class, and call the method. The error goes away.

Also you shouldn't name your class Frame as there is already an AWT Frame class. You may run into problem.

Also, follow Java naming convention, method names begin with lower case letters i.e. buttonDemo(). Without looking at your class name, I was totally confused thinking the ButtonDemo() was the class constructor.