Static variable error in main function
Dont know why it would be doing this. It is bascially telling me that every class I call in my main function needs to be static which is crazy.
import javax.swing.*;
import java.awt.*;
class Frame extends JFrame
public Frame()
setTitle("My Empty Frame");
setSize(300,200);
setLocation(10,200);
this.show();
public class Main extends JFrame
public JFrame frame;
public Main()
frame = new JFrame();
public static void main(String[] args)
System.out.println("CS348 Project 1");
frame.setVisible(true); <--------------------ERROR
}Thanks for the help.
The problem (basically), is that you could do the following if you felt like it:
import javax.swing.*;
import java.awt.*;
class Frame extends JFrame
public Frame()
setTitle("My Empty Frame");
setSize(300,200);
setLocation(10,200);
this.show();
public class Main extends JFrame
public JFrame frame;
public Main()
frame = new JFrame();
public static void main(String[] args)
Main main1 = new Main();
Main main2 = new Main();
Main main3 = new Main();
//what frame is this talking about??
frame.setVisible(true); <--------------------ERROR
}What you would want instead is probably something like this:
Main main1 = new Main();
main1.getFrame().setVisible(true);This leads to a few other questions: why are you extending JFrame if you have a JFrame variable in the class? Does that class have a JFrame, or is it a JFrame? You should almost definitely go with the "have" answer.
Similar Messages
-
There may be more errors in here besides the static variable error. I made the methods static for the method call in my constructor Product(name, price). The purpose of this Class is to the the name and price of a product from user input, subtract 5.00 from the price, and return the new price. Please help!!!
public class Product
public Product(String name, double price)
String product;
price = Product.getPrice(price);
Double.toString(price);
//this.product = product;
product = Product.getName(name) + Product.getPrice(price);
public static String getName(String name)
System.out.println("What is their name?: ");
name = in.nextLine(); // I GET A NONSTATIC VARIABLE ERROR FOR variable "in" HERE.
return name;
public static double getPrice(double price)
this.price = price;
System.out.println("What is the price?: ");
price = in.nextDouble();
return price;
public double reducePrice()
price = price - 5.00;
return price;
public String getProduct()
product = new Product(name, price);
return product;
Scanner in = new Scanner(System.in);
public static String name;
//public double price;
}you not define the class member properly.
the class member is define before the constructor as
public class Product {
static Scanner in = new Scanner(System.in);
String product;
double price;
public static String name;
public Product(String name, double price) {
price = Product.getPrice(price);
Double.toString(price);
// this.product = product;
product = Product.getName(name) + Product.getPrice(price);
} -
I have been working on this file for 4 days now and I can't get past these errors.
Here's the whole project:
package toysmanager;
public class ToysManager {
//Method ToysManager
public ToysManager() {
//Method main
public static void main(String[] args) {
ToddlerToy Train1 = new ToddlerToy();
ToddlerToy Train2 = new ToddlerToy();
ToddlerToy Train3 = new ToddlerToy();
System.out.print("This is an object of type ToysManager");
Train1.PrintProductID();
Train2.PrintProductID();
Train3.PrintProductID();
public class ToddlerToy{
private int ProductID = 0;
private String ProductName = "";
private float ProductPrice = 0;
public ToddlerToy(int id,String name, float price){
ProductID = id;
ProductName = name;
ProductPrice = price;
//Method PrintProductID
public int PrintProductID(){
System.out.print("This method is PrintProductID in the class ToddlerToy");
System.out.print("Product ID is:" + ProductID);
return ProductID;
public String PrintProductName(){
System.out.print("This method is PrintProductName in the class ToddlerToy");
System.out.print("Product Name:" + ProductName);
return ProductName;
public float PrintProductPrice(){
System.out.print("This method is PrintProductPrice in the class ToddlerToy");
System.out.print("Product Price: $" + ProductPrice);
return ProductPrice;
And here are the errors:
"ToysManager.java": non-static variable this cannot be referenced from a static context at line 9, column 29
"ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 9, column 29
"ToysManager.java": non-static variable this cannot be referenced from a static context at line 10, column 29
"ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 10, column 29
"ToysManager.java": non-static variable this cannot be referenced from a static context at line 11, column 29
"ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 11, column 29
Any help would be appreciated as I am plainly not understanding this even with a book.Annie:
Could you help me understand the original ToyManager instructions more please? Not asking you to do the work for me I just do not understand exactly what they want me to do...
Assignment:
After you install JCreator, write a Java program, with a single class called ToysManager. The main method should print the name of the class, for example: "This is an object of type ToysManager."
(Hint: the process is very similar to the "Hello World!" program.)
Please add file (.java)
Group Portion:
Deliverables: two *.java files
As a group, add a second class called ToddlerToy to your ToysManager project.
Here are the requirements for the ToddlerToy:
* The class ToddlerToy is public and has a default constructor.
* It has one private attribute called ProductID (of type int).
* It has two public methods called SetProductId() and PrintProductId().
* The method SetProductId() assigns a value to the attribute ProductId. For now, the value is hard-coded.
* The method PrintProductId prints the value of the attribute ProductId.
* The class ToddlerToy has no main() method. In Java, there is only one main method for the entire program. In this case, the main method is in the ToysManager class.
Here are the requirements for the main method of the ToysManager class:
* Create an object called Train1 of class type ToddlerToy, using the default constructor.
* Call the methods SetProductId() and PrintProductId() to set then print the the value of ProductId.
* The first statement in each method should print the name of the method, for example: "This is method <method name> in class <class name>". This should help you trace the execution of your program. Feel free to comment out the print statement.
* On the Small Group Discussion Board, discuss your understanding of the concepts of class, object, constructor, method, and attribute.
* Give one example of a class (giving its name, attributes, and methods) that could be part of the shipping application.ANY help with this at all is greatly appreciated...a friend of mine found your post and used it to give me code snippets for help and I had no idea. Nearly got me in deep water...redoing the assignment but personally I find the next two assignments much easier to understand than this one. The instructions are confusing to me...can you point me in the right direction? -
I know that non-static variables cannot be refrenced from a static context and I see where this error is happening but I can't figure out why. It doesn't appear that I am cross referencing static and non-static variables.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class CookieStuff extends JFrame implements ActionListener
private final int XSIZE = 600;
private final int YSIZE = 300;
private JButton myButton;
private JButton myButton2;
private JLabel myLabel;
private JLabel myLabel2;
public JTextField myTextField;
* Constructor
public CookieStuff(String title)
super(title);
setSize(XSIZE,YSIZE);
myButton = new JButton("Bake cookies");
myButton2= new JButton("Eat cookies");
myLabel = new JLabel("Number of cookies left: ");
myLabel2= new JLabel("Enter # of cookies and select a button");
myTextField = new JTextField(5);
myButton.addActionListener(this);
myButton2.addActionListener(this);
add(myButton,BorderLayout.NORTH);
add(myButton2,BorderLayout.SOUTH);
add(myLabel,BorderLayout.WEST);
add(myLabel2,BorderLayout.EAST);
add(myTextField,BorderLayout.CENTER);
public static void welcomeStuff()
JOptionPane.showMessageDialog(null,"Welcome to grandma's cookie jar..");
public void actionPerformed(ActionEvent ev)
Object source = ev.getSource();
if(source == myButton)
if(CookieJar.bake() > CookieJar.COOKIES_ALLOWED)
JOptionPane.showMessageDialog(this, "Grandma's jar is too small for that many cookies");
else
JOptionPane.showMessageDialog(this, CookieJar.bake());
myLabel.setText("Number of cookies left: " + (CookieJar.bake()));
else
if(CookieJar.eat() < 0)
JOptionPane.showMessageDialog(this, "There are not enough cookies in the jar fatso");
else
JOptionPane.showMessageDialog(this, CookieJar.eat());
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class CookieJar
public static final int COOKIES_ALLOWED = 40;
public int numOfCookies;
public int cookieCount;
public CookieJar()
cookieCount = numOfCookies;
numOfCookies++;
public int eat()
int numOfCookies = 0;
numOfCookies = (numOfCookies - Integer.parseInt(CookieStuff.myTextField.getText()));
return numOfCookies;
public int bake()
int numOfCookies = 0;
numOfCookies = (numOfCookies + Integer.parseInt(CookieStuff.myTextField.getText()));
return numOfCookies;
}The last 2 methods eat( ) and bake( ) are giving the errors. Thanks.C:\Documents and Settings\Travis Mandrell\Desktop\DePaul\CSC212\hw8\CookieStuff.java:49: non-static method bake() cannot be referenced from a static context
if(CookieJar.bake() > CookieJar.COOKIES_ALLOWED)
^
C:\Documents and Settings\Travis Mandrell\Desktop\DePaul\CSC212\hw8\CookieStuff.java:55: non-static method bake() cannot be referenced from a static context
JOptionPane.showMessageDialog(this, CookieJar.bake());
^
C:\Documents and Settings\Travis Mandrell\Desktop\DePaul\CSC212\hw8\CookieStuff.java:56: non-static method bake() cannot be referenced from a static context
myLabel.setText("Number of cookies left: " + (CookieJar.bake()));
^
C:\Documents and Settings\Travis Mandrell\Desktop\DePaul\CSC212\hw8\CookieStuff.java:62: non-static method eat() cannot be referenced from a static context
if(CookieJar.eat() < 0)
^
C:\Documents and Settings\Travis Mandrell\Desktop\DePaul\CSC212\hw8\CookieStuff.java:68: non-static method eat() cannot be referenced from a static context
JOptionPane.showMessageDialog(this, CookieJar.eat());
^
.\CookieJar.java:21: non-static variable myTextField cannot be referenced from a static context
numOfCookies = (numOfCookies - Integer.parseInt(CookieStuff.myTextField.getText()));
^
.\CookieJar.java:28: non-static variable myTextField cannot be referenced from a static context
numOfCookies = (numOfCookies + Integer.parseInt(CookieStuff.myTextField.getText()));
^
7 errors -
Static variable doubt !!!
why the following code throws an error (Illegal start of expression )
public class samp
public static void main(String [] a)
static int i=10; // error is occuring at this line ....
System.out.println(i);
}In C you can have a static variable declared inside a function.
It is static, that is, retains the value between the calls, and it is declared in the function, hence it is seen only from there. In the following example both function have their own static i variables.
#include <stdio.h>
static int i=0;
int foo() {
static int i=100;
return i++;
int bar() {
static int i=200;
return i++;
int main() {
int x;
for(x=4;x<8;x++) printf("%d %d\n",x,foo());
for(x=4;x<8;x++) printf("%d %d\n",x,bar());
printf("%d\n",i);
} -
Error on compile - non-static variable can not be referencedfrom static con
Error on compile happening with addButton?
Thanks
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
public class Log implements ActionListener {
JButton addButton;
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridy = 3;
c.gridx = 0;
JLabel callsignLabel= new JLabel("Callsign");
pane.add(callsignLabel, c);
c.gridy = 3;
c.gridx = 1;
JLabel nameLabel= new JLabel("Name");
pane.add(nameLabel, c);
c.gridy = 3;
c.gridx = 2;
JLabel timeLabel= new JLabel("Time");
pane.add(timeLabel, c);
c.gridy = 3;
c.gridx = 3;
JLabel dateLabel= new JLabel("Date");
pane.add(dateLabel, c);
c.gridy = 3;
c.gridx = 4;
JLabel frequencyLabel= new JLabel("Freq ");
pane.add(frequencyLabel, c);
c.gridy = 3;
c.gridx = 5;
JLabel locationLabel = new JLabel("Country/State");
pane.add(locationLabel, c);
c.gridy = 5;
c.gridx = 0;
addButton = new JButton("Add");
pane.add(addButton, c);
addButton.addActionListener(this);Thank you for the reply
I am new to Java
What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again. -
Main method hangs setting static variable
I have a very annoying intermittent problem. Once in a while (roughly 1 out of 30 times), my app hangs in the main method when assigning a value to a static variable.
public static void main(String[] args) {
//read args
//do some very trivial stuff (never hangs here)
someOtherNonStaticClass.aStaticInt = 100;//once in a while it hangs here???
}I have tried setting "-Dsun.java2d.noddraw=true" but this hasnt helped. I have tried using JRE 1.4.1 and 1.4.2 and they both have this problem. Some machines seem to be worse than others but this may just be chance.
When the app hangs, it appears in task manager as a javaw.exe process, but the app itself doesnt appear.
Does anyone have any ideas or suggestions for me to try? Its pretty annoying not have a stack trace to work with.I have tried setting "-Dsun.java2d.noddraw=true" butWhy should it?
this hasnt helped. I have tried using JRE 1.4.1 and
1.4.2 and they both have this problem. Some machines
seem to be worse than others but this may just be
chance.
When the app hangs, it appears in task manager as a
javaw.exe process, but the app itself doesnt appear.That's normal. All Java apps would appear as javaw.exe. Because the JVM has the process.
Does anyone have any ideas or suggestions for me to
try? Yes. Stop accessing fields of another class. It's bad design to begin with, and it looks to me like you're breaking something someplace else by setting that value to 100 right then. -
Runtime error in linking with static variables....
Hi,
I am building a shared library which includes a compiled object generated from a class containing the static variables only and also I have another version of same class with same & some new static variables in it and using that to generate another shared library. Now when I tried to run a program
which links with both the library it core dumps when it tries to return from the program i.e when it finishes.
Can someone please help me explain why my program is behaving like that?? Can duplicate inculsion of static variables in different scope can cause problem ?? How can this be avoided ?
Also please be advised that the class with static variables gets generated at the compile time using a script which uses a DTD whose version (specification) can be different in both the libraries therefore I can't just seperate the common stuff into one class and specific into another.
Thanks.
Rajeev.Not to worry...found the answer in another post. Seems like patches need to applied to the OS.
-
Static variable declaration in JavaFX
Hello, I'd like to ask how to substitute static key word to declare a variable, that is visible within the current package and accessible without creating an instance of a class, that contains this variable. Because my NetBeans insists that static variable is depricated.
Thank you.In Foo.fx...
class Foo {
// bar is an instance variable that has public access
public def bar = "bar";
// baz is a "static" variable that has public access
public def baz = "baz";
// someFun is a "static" function
public function someFun() : Void {
}In Main.fx...
println("{Foo.bar}"); // compile error - cannot reference bar from static context
println("{Foo.baz}"); // This is ok - Foo.baz is static
var foo = Foo{}
println("{foo.bar}"); // This is ok. bar referenced from Foo instance -
Non-static variable Help needed
Hi, I am creating a multi threaded web server but get the following error
non-static variable this cannot be referenced from a static context
HttpRequest request = new HttpRequest(connectionSocket);
Please could someone help.
Many Thanks
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class MultiWebServer
public static void main(String argv[]) throws Exception
// Set the port number.
int port = 6789;
// Establish the listen socket.
String fileName;
ServerSocket listenSocket = new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while (true) {
// Listen for a TCP connection request.
Socket connectionSocket = listenSocket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request = new HttpRequest(connectionSocket);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
final class HttpRequest implements Runnable
final static String CRLF = "\r\n";
Socket socket;
String requestMessageLine;
String fileName;
Date todaysDate;
// Constructor
public HttpRequest(Socket socket) throws Exception
this.socket = socket;
socket = null;
// Implement the run() method of the Runnable interface.
public void run()
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
private void processRequest() throws Exception
// Get a reference to the socket's input and output streams.
//InputStream is = new InputStream(socket.getInputStream());
//DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
socket.getOutputStream());
// Set up input stream filters.
requestMessageLine = inFromClient.readLine();
//BufferedReader br = null;
// Get the request line of the HTTP request message.
String requestLine = null;
// Display the request line.
System.out.println();
System.out.println(requestLine);
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET"))
fileName = tokenizedLine.nextToken();
if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".jpeg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: text/html\r\n");
if (fileName.endsWith(".htm"))
outToClient.writeBytes("Content-Type: text/html\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
socket.close();
else
System.out.println("Bad Request Message");
todaysDate = new Date();
try {
FileInputStream inlog = new FileInputStream("log.txt");
System.out.println(requestMessageLine + " " + todaysDate );
FileOutputStream log = new FileOutputStream("log.txt", true);
PrintStream myOutput = new PrintStream(log);
myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
catch (IOException e) {
System.out.println("Error -> " + e);
System.exit(1);
socket.close();import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class MultiWebServer
public MultiWebServer(){
try{
// Set the port number.
int port=6789;
// Establish the listen socket.
String fileName;
ServerSocket listenSocket=new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while(true){
// Listen for a TCP connection request.
Socket connectionSocket=listenSocket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request=new HttpRequest(connectionSocket);
// Create a new thread to process the request.
Thread thread=new Thread(request);
// Start the thread.
thread.start();
}catch(IOException ioe){
}catch(Exception e){
public static void main(String argv[]) throws Exception
new MultiWebServer();
final class HttpRequest implements Runnable
final static String CRLF = "\r\n";
Socket socket;
String requestMessageLine;
String fileName;
Date todaysDate;
// Constructor
public HttpRequest(Socket socket) throws Exception
this.socket = socket;
socket = null;
// Implement the run() method of the Runnable interface.
public void run()
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
private void processRequest() throws Exception
// Get a reference to the socket's input and output streams.
//InputStream is = new InputStream(socket.getInputStream());
//DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
socket.getOutputStream());
// Set up input stream filters.
requestMessageLine = inFromClient.readLine();
//BufferedReader br = null;
// Get the request line of the HTTP request message.
String requestLine = null;
// Display the request line.
System.out.println();
System.out.println(requestLine);
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET"))
fileName = tokenizedLine.nextToken();
if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".jpeg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: text/html\r\n");
if (fileName.endsWith(".htm"))
outToClient.writeBytes("Content-Type: text/html\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
socket.close();
else
System.out.println("Bad Request Message");
todaysDate = new Date();
try {
FileInputStream inlog = new FileInputStream("log.txt");
System.out.println(requestMessageLine + " " + todaysDate );
FileOutputStream log = new FileOutputStream("log.txt", true);
PrintStream myOutput = new PrintStream(log);
myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
catch (IOException e) {
System.out.println("Error -> " + e);
System.exit(1);
socket.close(); -
To use a static variable in another class,but report NullPointerException
when TableMain is running,I run testRecord so that let TableMain add a occur informatin and
happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping me to check my code;(error report info is in end)
import java.awt.event.*;
import javax.swing.table.*;
import java.io.*;
public class TableMain extends JFrame{
JTable table;
static OwnModel model;
String[] columnHeader={"occur","time"};
class OwnModel extends DefaultTableModel{
public OwnModel(Object[] columnNames,int numRows){
super(columnNames,numRows);
public boolean isCellEditable(int row,int column){
return false;
public TableMain(){
model=new OwnModel(columnHeader,0);
table=new JTable(model);
JScrollPane scroll=new JScrollPane(table);
JButton save=new JButton("save record");
JButton delete=new JButton("delete record");
JPanel buttons=new JPanel();
buttons.add(save);
buttons.add(delete);
JLabel sign=new JLabel("occur record");
Container cp=getContentPane();
cp.add(BorderLayout.NORTH,sign);
cp.add(BorderLayout.CENTER,scroll);
cp.add(BorderLayout.SOUTH,buttons);
this.setSize(300,500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static void main(String[] args){
new TableMain();
import java.util.Vector;
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class testRecord{
public static void main(String[] args){
SimpleDateFormat simpledf=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String tableName="friends";
Calendar occurtime=Calendar.getInstance();
Vector record=new Vector();
record.add("send 'desc' sql, "+"operated table is :"+tableName);
record.add(simpledf.format(occurtime.getTime()));
System.out.println("model is "+Guide.model);
System.out.println("record is "+record);
Guide.model.addRow(record);
error report:
model is null
record is [send 'desc' sql,operated table is :friends, 2004/05/26 11:39:03]
Exception in thread "main" java.lang.NullPointerException
at testRecord.main(testRecord.java:14)but I just use this constructor once,never use twice
with same jvm;I thinks my idea is not too very badIt's a public constructor (if I'm looking in the right
place) - it could be called from anywhere. To
intialize a static variable outside the declaration,
use a static initializer:private static String whatever;static {
whatever = "whatever";
}Or simply (in this case):private static String whatever = "whatever"; -
Non-static variable cant accessed from the static context..your suggestion
Once again stuck in my own thinking, As per my knowledge there is a general error in java.
i.e. 'Non-static variable cant accessed from static context....'
Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
i.e.
public class trial{
���������� public static void main(String ar[]){ ////static context
������������ int counter=0; ///Non static variable
������������ for(;counter<10;) {
�������������� counter++;
�������������� System.out.println("Value of counter = " + counter) ; ///working fine
�������������� }
���������� }
Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
Please give your valuable suggestions.
Thanks,
JeffOnce again stuck in my own thinking, As per my
knowledge there is a general error in java.
i.e. 'Non-static variable cant accessed from static
context....'
Now the thing is that, When we are declaring any
variables(non-static) and trying to access it within
the same method, Its working perfectly fine.
i.e.
public class trial{
���������� public static void
main(String ar[]){ ////static context
������������ int counter=0; ///Non
static variable
������������ for(;counter<10;) {
�������������� counter++;
��������������
System.out.println("Value
of counter = " + counter) ; ///working fine
�������������� }
���������� }
w the question is that if we are trying to declare a
variable out-side the method (Non-static) , Then we
defenately face the error' Non-static varialble can't
accessed from the static context', BUT here within
the static context we declared the non-static
variable and accessed it perfectly.
Please give your valuable suggestions.
Thanks,
JeffHi,
You are declaring a variable inside a static method,
that means you are opening a static scope... i.e. static block internally...
whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
But if you put ... it will be considered as redundant by compiler.
More over, static context does not get "this" pointer...
that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller. -
Non-static variable from a static context
This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
The error...
Googler.java:27: non-static variable this cannot be referenced from a static context
submitButton.addActionListener(new ButtonHandler());The code...
JButton submitButton = new JButton("Submit Query");
submitButton.addActionListener(new ButtonHandler());thanks for the response.
I have already tried what you said but I tried it again anyway and i get the same error more less...
Googler.java:28: non-static variable this cannot be referenced from a static context
ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
public class Googler
static JTextField input1, input2;
public static void main(String[] args)
JFrame myFrame = new JFrame("Googler v1.0");
Container c = myFrame.getContentPane();
JLabel lab1 = new JLabel("Enter Google Query:");
JLabel lab2 = new JLabel("Enter Unique API Key:");
input1 = new JTextField(15);
input2 = new JTextField(15);
JRadioButton radSearch = new JRadioButton("Search Query");
JRadioButton radCached = new JRadioButton("Cached Query");
JButton submitButton = new JButton("Submit Query");
ButtonHandler buttonHandler = new ButtonHandler();
submitButton.addActionListener(buttonHandler);
ButtonGroup group = new ButtonGroup();
group.add(radSearch);
group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
Thanks
Lee -
Non static variable in static context
import java.util.Scanner;
public class project4_5 {
int die1, die2;
int comptotal = 0, playertotal = 0, turntotal = 0;
int turn, comprun = 0;
String playername;
String action = ("R");
Scanner scan = new Scanner(System.in);
public static void main (String[] args)
PairOfDice mydie = new PairOfDice();
System.out.println("!!!!!!PIG!!!!!!");
System.out.println();
System.out.println("Enter your name! ");
playername = scan.nextLine();
while(playertotal>100 && comptotal>100){
while(action.equalsIgnoreCase("R")){
System.out.println(playername+" roll or pass the die (R/P) ");
action = scan.nextLine();
if(action.equalsIgnoreCase("P"))
break;
mydie.roll();
die1 = mydie.getFace1();
die2 = mydie.getFace2();
System.out.println("You rolled a "+die1+" and a "+ die2);
if(die1==1||die2==1){
turntotal = 0;
System.out.println("You rolled a 1, you lose your points"
+" for this turn.");
break;
else if(die1==1&&die2=1){
playertotal = 0;
System.out.println("You rolled snake eyes, all points have"
+ " been lost.");
break;
else
turntotal= turntotal+die1+die2;
System.out.println("Would you like to roll or pass? (R/P)");
if(action.equalsIgnoreCase("P")){
playertotal = playertotal+turntotal;
turntotal = 0;
while(turntotal<=20||turns!=run){
turn = (int) (Math.random() * 5 + 1);
mydie.roll();
die1 = mydie.getFace1();
die2 = mydie.getFace2();
System.out.println("Computer rolled a "+die1+
" and a "+ die2);
if(die1==1||die2==1){
turntotal = 0;
System.out.println("Computer rolled a 1 he loses hi points"
+" for this turn.");
break;
else if(die1==1&&die2=1){
playertotal = 0;
System.out.println("Computer rolled snake eyes, his points have"
+ " been lost.");
break;
else
turntotal= turntotal+die1+die2;
comprun++;
turntotal = 0;
}here is code for a dice game i made...and when i compile it practically every variable gets an error saying non-static variable can not be referenced from a static context....anyone kno what this means or how i go about fixing it...i think it has something to do with assigning the return variable from my getFace method to die1 and die 2...idk how to fix it tho
if u need it my die class is below
public class PairOfDice
int faceValue1, faceValue2;
public PairOfDice()
faceValue1 = 1;
faceValue2 = 1;
public void roll()
faceValue1 = (int) (Math.random() * 6 + 1);
faceValue2 = (int) (Math.random() * 6 + 1);
public int getFace1 ()
return faceValue1;
public int getFace2 ()
return faceValue2;
It means what it says -- that you're trying to use a non-static thing (like a method or a field) from a static thing (like your main method).
You can either make everything static (which isn't great -- it flies in the face of object-oriented programming) or instantiate an object.
If you want to do the latter, then try this: make your main method instantiate a method, and run it, like this:
public static void main(String[] argv) {
project4_5 game = new project4_5();
game.play();
}Then create a method called play:
public void play() {
// put everything that's currently in main() in here
}See if that fixes it for you. -
Help me please~ non-static variable rs cannot be referenced ...
i make counter
but this error occurrence
only i doing resultset make and closed
why non-static variable rs ....
i am sorry i don't speak English ...
help me please..
error message
non-static variable rs cannot be referenced from a static context
source
===============================================
package jjaekim;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count{
Statement stmt;
ResultSet rs;
ResultSet rs2;
Connection conn;
//DBPoolManager dbpm;
public static String add(HttpServletRequest request){
try{
int year =0;
int month=0;
int date =0;
int hour =0;
int min =0;
int week =0;
String str_date=new String();
String str_time=new String();
String referer_url =request.getHeader("Referer");
String infomation =request.getHeader("User-Agent");
String ip =request.getRemoteAddr();
int access_date=0;
int access_time=0;
Calendar cal =Calendar.getInstance();
year =cal.get(cal.YEAR);
month =cal.get(cal.MONTH) + 1;
date =cal.get(cal.DATE);
hour =cal.get(cal.HOUR_OF_DAY);
min =cal.get(cal.MINUTE);
week =cal.get(cal.DAY_OF_WEEK);
access_date =(month*100)+date;
access_time =(hour*100)+min;
if(access_date<1000)
str_date="0"+new Integer(access_date).toString();
else
str_date=new Integer(access_date).toString();
if(access_time<100)
str_time="0"+new Integer(access_time).toString();
else
str_time="0"+new Integer(access_time).toString();
}catch(Exception e){
//System.out.print("Exc"+e.getMessage());
//return false;
finally{
if(rs!=null){
try{ rs.close();}catch(Exception e){}
if(rs2!=null){
try{ rs2.close();}catch(Exception e){}
if (stmt!=null){
try{ stmt.close();}catch(Exception e){}
//if (conn!=null){
try{ conn.close(); }catch(Exception e){}
//return back;
/* public static void main(String[] args)
System.out.println("Hello World!");Hello jjaekim,
if rs is a class variable (the same value for all objects),
try this (more likely to be the right solution) :
static ResultSet rs;
instead of :
ResultSet rs;
if rs has a different values in different objects,
then you should add the object name when using it like this :
myObject.rs or this.rs
Maybe you are looking for
-
Playback Screen turns Green. Audio is fine but no Video
I have been trying to find a solution on the web but can't seem to find the answer that will help my case of the FCP playback screen turns green with no video. Audio plays back fine. Everything was working fine until today. Something changed - what d
-
Zone create not installing all zone root files
I'm installing a new T5240 Solaris 10 u6 10/08 with the 10_Recommended patch kit from 09 Dec 2008. The system is jumpstarted with /, /usr, /var, /export/home on SVM mirrored internal 146g drives. When I first got the server up and running, I tested z
-
Airport utility was unable to find any airport wireless device
Installed Airport Extreme connected to my PC running XP Pro. Configured my wireless network successfully. Updated to Aiport Utility for Windows ver 5.5.2 and the Airport Utility shows the 'unable to find an Airport wireless device' message and the 'R
-
Linux or Ubuntu on an S10 Netbook
I have a Lenovo S10. It runs great, but in the spirit of gadgetry and curiosity, I would like to see what Linux or Ubuntu would be like on my S10. I would love to be able to boot it up from a USB drive. I have tried to read and understand the variou
-
When opening a new tab, how do I make firefox automatically switch to it?
Pressing Control+T or the "+" button next to tabs will open the new tab. However, I want the new tab to be automatically selected when it is generated. Right clicking links and Opening in new tab works fine.