Painting jpeg in java application: non-static method ... static context
Hi!
I simply want to show a jpeg within a java application. Showing the jpeg in an applet is no problem (see code below). But I have difficulties to translate this code to a java application. No matter what I try to load the jpeg, I end up with the following error:
non-static method createImage() cannot be referenced from a static context
How can I surround it? Thanx in advance for your help!
Working applet
import java.applet.*;
import java.awt.*;
public class shJpAp extends javax.swing.JApplet {
Image pic;
/** Creates a new instance of shJpAp */
public shJpAp() {
public void init() {
pic=getImage(getCodeBase(), "lemmer.jpg");
prepareImage(pic,this);
public void paint (Graphics g) {
g.drawImage(pic,0,0,this);
Application
import java.awt.*;
public class shJp extends javax.swing.JFrame {
Image pic;
/** Creates new form shJp */
public shJp() {
initComponents();
//pic = java.awt.Toolkit.getImage("lemmer.jpg");
---> pic = java.awt.Toolkit.createImage("lemmer.jpg");
---> prepareImage(pic, this);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
private void initComponents() {
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
pack();
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
* @param args the command line arguments
public static void main(String args[]) {
new shJp().show();
// Variables declaration - do not modify
// End of variables declaration
public void paint( Graphics g) {
g.drawImage(pic, 0,0,this);
}
Hi,
just want to add a solution I found in some textbook (see code below). I hate finding every possible question in the internet, but seldom fitting answers.....
But again, one little thing pushed me close to my first heart attack: The code below works well when executed by foot (...java showPic...). In the NetBeans 3.6 the frame refuses to show the pic!
I am looking for an appropiate forum - but if anyone of you can help, it would be very nice ;-)
import java.awt.*;
import java.awt.event.*;
public class showPic extends Frame {
Image pic;
public showPic() {
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
pic = getToolkit().getImage("lemmer.jpg");
setSize(200,100);
setVisible(true);
public void paint(Graphics g) {
if (pic != null) {
g.drawImage(pic,60,20,this);
public static void main( String[] args ) {
new showPic();
}
Similar Messages
-
Java cognoscenti,
Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a differenceNo, it's not the same. You are not "defering the
implementation of a static method" because static
methods are never polymorphic.
Static methods cannot be abstract for this reason, and
only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
A short summary of what I've learnt so far:
- interfaces cannot contain static methods
- abstract classes cannot contain abstract static methods
- static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
/* output
SuperClass.someMethod()
SubClass.someMethod()
SuperClass.someMethod()
SuperClass.someMethod()
SubClass.someMethod()
SubClass.someMethod()
SuperClass.someMethod()
public class Test {
public final static void main(String[] args) {
// output: SuperClass.someMethod()
new SuperClass().someMethod();
// output: SubClass.someMethod()
new SubClass().someMethod();
// output: 2x SuperClass.someMethod()
SuperClass someClass1 = new SubClass();
someClass1.someMethod();
showSuper(someClass1);
// output: 2x SubClass.someMethod()
SubClass someClass2 = new SubClass();
someClass2.someMethod();
showSub(someClass2);
showSuper(someClass2); // SuperClass.someMethod()
public final static void showSuper(SuperClass c) {
c.someMethod();
public final static void showSub(SubClass c) {
c.someMethod();
class SuperClass {
public static void someMethod() {
System.out.println("SuperClass.someMethod()");
class SubClass extends SuperClass {
public static void someMethod() {
System.out.println("SubClass.someMethod()"); -
Non-static method paint cannot be referenced from static context
i cant seem to figure out this error dealing method paint:
public class TemplateCanvas extends Canvas implements Runnable {
//static
public static final int STATE_IDLE = 0;
public static final int STATE_ACTIVE = 1;
public static final int STATE_DONE = 2;
private int width;
private int height;
private Font font;
private Command start;
private int state;
private String message;
public TemplateCanvas() {
width = getWidth();
height = getHeight();
font = Font.getDefaultFont();
//// set up a command button to start network fetch
start = new Command("Start", Command.SCREEN, 1);
addCommand(start);
public void paint(Graphics g) {
g.setColor(0xffffff);
g.fillRect(0, 0, width, height);
g.setColor(0);
g.setFont(font);
if (state == STATE_ACTIVE) {
Animation.paint(g);
} else if (state == STATE_DONE) {
g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
public void commandAction(Command c, Displayable d) {
if (c == start) {
removeCommand(start);
//// start fetching in a new thread
Thread t = new Thread(this);
t.start();
public void run() {
state = STATE_ACTIVE;
//// start network fetch
Network network = new Network();
network.start();
//// start busy animation
Animation anim = new Animation(this);
anim.start();
//// wait for network to finish
synchronized (network) {
try {
wait();
} catch (InterruptedException ie) { }
//// end animation
anim.end();
//// get message from network
message = network.getResult();
//// repaint message
state = STATE_DONE;
repaint();
}TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static contextAnimation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.
-
Calling a non-static method from another Class
Hello forum experts:
Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
populates a JTable.
2. User selects a row in the table and then clicks a button on the icon toolbar
which is part of UIMenu class.
3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
(a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
== OR ==
(b). I could declare UpdateDatabase() as static and call this method without
creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
object specific data.
With option (b), if I declare the method as static, the variables used in the method would also have to be static.
The variables, in which case, would not be object specific.
Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
way?
Any ideas or thoughts will be of tremendous help. Thanks in advance.Hello Forum:
Danny_From_Tower, Encephalatic: Thank you both for your responses.
Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
and declared as public.
public class MyMenu {
public JButton btnAccept;
//Constructor
public MyMenu() {
btnAccept = new JButton("Accept");
} I instantiate an object for MyMenu class in the main application class MyApp.
public class MyApp {
private MyMenu menu;
//Constructor
public MyApp(){
menu = new MyMenu();
public void openOrder(){
MyGUI MyIntFrame = new MyGUI(menu.btnAccept);
}I pass this button all the way down to the class detail02. Now I want to set up a listener for this
button in the class detail02. I am not able to do this.
public class MyGUI {
private JButton acceptButton;
private detail02 dtl1 = new detail02(acceptButton);
//Constructor
public AppGUI(JButton iButton){
acceptButton = iButton;
public class detail02{
private JButton acceptButton;
//Constructor
public detail02(JButton iButton){
acceptButton = iButton;
acceptButton.addActionListener(new acceptListener());
//method
private void acceptListener_actionPerformed(ActionEvent e){
System.out.println("Menu item [" + e.getActionCommand( ) + "] was pressed.");
class acceptListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
acceptListener_actionPerformed(e);
} I am not able to get the button Listener to work. I get NullPointerException at this line
acceptButton.addActionListener(new acceptListener());in the class detail02.
Is this the right way? Or is there a better way of accomplishing my objective?
Please help. Your inputs are precious! Thank you very much for your time! -
Abstract method versus static and non-static methods
For my own curiosity, what is an abstract method as opposed to static or non-static method?
Thanks>
Following this logic, is this why the "public static
void main" 0r "Main" method always has to be used
before can application can be run: because it belongs
to the class (class file)?
Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
RObin -
Using a non-static vector in a generic class with static methods
I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
package genericset;
import java.util.*;
public class GenericSet<E>{
private Vector v;
public GenericSet(Vector vec) {
v = vec;
private <T extends Comparable> Item<T> get(int index) {
return (Item<T>) v.get(index);
public static <T extends Comparable> GenericSet<T> initialize() {
return new GenericSet<T>(new Vector());
public Vector getVector() {
return v;
public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
GenericSet<T> g = assign(z);
Vector v = g.getVector();
if (!member(g,i))
v.addElement(i);
return g;
public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
GenericSet<T> g = assign(z);
Vector v = g.getVector();
if (member(g,i))
v.remove(i);
return g;
public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
Vector v = z.getVector();
return v.contains(i);
public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
Vector v1 = z1.getVector();
Vector v2 = z2.getVector();
if((v1 == null) && (v2 != null))
return false;
return v1.equals(v2);
public static <T extends Comparable> boolean empty(GenericSet<T> z) {
return (cardinality(z) == 0);
public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
GenericSet<T> g = assign(z1);
for(int i=0; i<cardinality(z2); i++) {
Item<T> elem = z2.get(i);
insert(g, elem);
return g;
public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
GenericSet<T> g = initialize();
for(int i=0; i<cardinality(z2); i++) {
Item<T> elem = z2.get(i);
if(member(z1, elem))
insert(g, elem);
return g;
public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
GenericSet<T> g = initialize();
for(int i=0; i<cardinality(z1); i++) {
Item<T> elem = z1.get(i);
if(!member(z2, elem))
insert(g, elem);
for(int i=0; i<cardinality(z2); i++) {
Item<T> elem = z2.get(i);
if(!member(z1, elem))
insert(g, elem);
return g;
public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
GenericSet<T> g = initialize();
for(int i=0; i<cardinality(z); i++) {
Item<T> elem = z.get(i);
insert(g, elem);
return g;
public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
for(int i=0; i<cardinality(z1); i++) {
Item<T> elem = z1.get(i);
if(!member(z2, elem))
return false;
return true;
public static <T extends Comparable> int cardinality(GenericSet<T> z){
Vector v = z.getVector();
return v.size();
}The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this: public static EditorBean findEditorData( String username, EditorBean editorData )
return editorData.ed.findEditor( username );
} -
Non-static method cannot be referenced from a static context
Hey
Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
import java.io.*;
import java.util.*;
public class Trent
String processArray[][]=new String[20][2];
public static void main(String args[])
String fName;
System.out.print("Enter File Name:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
fName="0";
while (fName=="0"){
try {
fName = br.readLine();
System.out.println(fName);
readFile(fName);
catch (IOException ioe)
System.out.println("IO error trying to read File Name");
System.exit(1);
public void readFile(String fiName) throws IOException {
File inputFile = new File(fiName); //open file for reading
FileReader in = new FileReader(inputFile); //
BufferedReader br = new BufferedReader(
new FileReader(inputFile));
String first=br.readLine();
System.out.println(first);
StringTokenizer st = new StringTokenizer(first);
while (st.hasMoreTokens()) {
String dat1=st.nextToken();
int y=0;
for (int x=0;x<=3;){
processArray[y][x] = dat1;
System.out.println(y + x + "==" + processArray[y][x]);
x++;
}Hi am getting the same error in my jsp page:
Hi,
my adduser.jsp page consist of form with field username,groupid like.
I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
<% String USERID=request.getParameter("id");
String NAME=request.getParameter("name");
String GROUPID=request.getParameter("group");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
PreparedStatement st;
st = con.prepareStatement("Insert into user values (1,2,4)");
st.setString(1,USERID);
st.setString(2,GROUPID);
st.setString(4,NAME);
// PreparedStatement.executeUpdate();//
}catch(Exception ex){
System.out.println("Illegal operation");
%>
But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
Really Speaking I am newbie in this java world.
whether you have any other solution for above issue?
waiting Your valuable suggestion.
Thanks and regards
haresh -
Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
public class BankAccount {
private static int nextAccountNumber = 1000;
//used to generate account numbers
private String owner; //name of person who owns the account
private int accountNumber; //a valid and unique account number;
private double balance; //amount of money in the account
private TransactionHistory transactions; //collection of past transactions
private Transaction transaction;
//constructor
public BankAccount(String anOwnerName){
owner = anOwnerName;
accountNumber = nextAccountNumber++;
balance = 0.0;
transactions = new TransactionHistory();
//public String getOwner() {
public void deposit(double anAmount ){
balance=balance+anAmount;
transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
transactions.add(transaction);
//public void withdraw(double anAmount){
//public String toString() {
***public void printHistory(){
TransactionHistory.printHistory();
AND
public class TransactionHistory {
final static int CAPACITY = 6; //maximum number of transactions that can be remembered
//intentionally set low to make testing easier
private Transaction[] transactions = new Transaction[CAPACITY];
//array to store transaction objects
private int size = 0;
//the number of actual Transaction objects in the collection
public void add(Transaction aTransaction){
if (size>5){
transactions[0]=transactions[1];
transactions[1]=transactions[2];
transactions[2]=transactions[3];
transactions[3]=transactions[4];
transactions[4]=transactions[5];
transactions[5]=aTransaction;
transactions[size]=aTransaction;
size=size++;
public int size() {
return size;
***public void printHistory() {
for(int i=0;i<6;i++){
System.out.println(transactions);
//public void printHistory(int n){
The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
~ -
Non-static method setUp() cannot be referenced (error)
Hi;
I have this error
"findContainer.java": non-static method setUp() cannot be referenced from a static context at line 10, column 26
everytime i am trying to make this call
jade.core.AddContTry.setUp();in
public class findContainer {
public findContainer() {}
public void sUp(){
System.out.println("please wait, this is first try to find he agents in the main container"+"\n");
jade.core.AddContTry.setUp();
this setup() method
is written as follows
public void AddContTry () {
public void setUp(){
AID[] list= null;
try {
MyMainContainer = myprofile.getMain();
System.out.println("\n"+"This is the new container created in case of failure"+"\n");
list = MyMainCont.agentNames();
for (int i=0; i<list.length; i++){
System.out.println("names = " + list.toString() + " \n");
catch (ProfileException pe) { System.out.println("there is not main container");
could you please help me?My guess is that it is throwing a NullPointerException because you have not set 'a' to be anything.
The sample code you provided does not make sense.
AddContTry is a method in the code but you are using it like a class.
You have to set the following before you can use the object 'a'
AddContTry a = // something
I am just guessing here but can you write
AddContTry a = new AddContTry();
a.setUp();
Note, If this is the case, the code in setUp should be in the constructor. -
Non-static method getRealPath cannot be referenced from a static context
Hi, I'm fairly new to java and servlets, I get the following error referencing the line denoted in the code snippet with a ">>" I don't understand why I am getting this error message?
Message: non-static method getRealPath(java.lang.String) cannot be referenced from a static context
public class events extends HttpServlet implements SingleThreadModel {
private static final String CONTENT_TYPE = "text/html";
//Initialize global variables
public Document xmlDocument;
public HttpSession theSession;
public RequestDispatcher pageInit;
public RequestDispatcher pageHeader;
public RequestDispatcher pageFooter;
public String path;
public void setPath(){
path = getServletContext.getRealPath( "/" ); }
public void init() throws ServletException {
}Ok More Code, I am weary of posting too much? I don't know why come to think of it?
package altitude;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.jdom.*;
import altitude.sysVar;
public class events extends HttpServlet implements SingleThreadModel {
private static final String CONTENT_TYPE = "text/html";
//Initialize global variables
public Document xmlDocument;
public HttpSession theSession;
public RequestDispatcher pageInit;
public RequestDispatcher pageHeader;
public RequestDispatcher pageFooter;
public String path;
public void getRealPath(){
path = ServletContext.getRealPath( "/" );
public void init() throws ServletException {
//Process the HTTP Get request
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
//Initialise some Global Variables
theSession = request.getSession( true );
doPage( request, response );
//Process the HTTP Post request
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
//Initialise some Global Variables
theSession = request.getSession( true );
doPage( request, response );
public void doPage( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
//Initialise the variables and get the parameters from the query string.
String eventID = request.getParameter( "eventID" );
String dateFrom = request.getParameter( "dateFrom" );
String dateTo = request.getParameter( "dateTo" );
theSession.setAttribute( "Page Title", sysVar.servletTitle_events);
Calendar theCalendar = Calendar.getInstance();
RequestDispatcher pageInit = request.getRequestDispatcher( sysVar.servlet_initSession );
pageInit.include( request, response );
RequestDispatcher pageHeader = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_header );
RequestDispatcher pageBody = request.getRequestDispatcher( sysVar.servletJsp_events );
RequestDispatcher pageFooter = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_footer );
//Initailize the site for this visitor this sets up the skin, and any customisations that may exist.
//load variables, objects in to the session
theSession.setAttribute( "Xml Document Object", path + sysVar.data_events );
pageHeader.include( request, response );
pageBody.include( request, response );
pageFooter.include( request, response );
//remove the variables and the objects from the session
theSession.setAttribute( "Xml Document Object", "" );
//Clean up resources
public void destroy() {
} -
What does this mean. I know about static, but I don't understand why I get this so many times.
I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
public class Test extends JFrame
public Test
setSize( 100, 100 );
show();
public static main( String args[] )
Test window = new Test();
draw();
public void draw()
blablabla whatever I want to do, a lot of times I can't.....
}Why is this, what is the reason for Java to forbid this and what can I do about it?Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
Test window = new Test();
// maybe some code to generate something to draw???
window.draw();
}This is what I think you are trying to do.
On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
Doug -
Non-static method getIDnumber() cannot be referenced from a static context
Student.java
public class Student
private int IDnumber;
private int hours;
private int points;
public Student()
IDnumber = 9999;
points = 12;
hours = 3;
public void setIDnumber(int number)
IDnumber = number;
public int getIDnumber()
return IDnumber;
public void setHours(int number)
hours = number;
public int getHours()
return hours;
public void setPoints(int number)
points = number;
public int getPoints()
return points;
public void showIDnumber()
System.out.println("ID Number is " + IDnumber);
public void showHours()
System.out.println("Credit Hours are " + hours);
public void showPoints()
System.out.println("Points Earned are " + points);
public double getGradePoint()
return (double) (points / hours);
ShowStudent.java
public class ShowStudent
public static void main(String[] args)
Student learner = new Student();
int IDnumber;
int points;
int hours;
IDnumber = Student.getIDnumber();
points = Student.getPoints();
hours = Student.getHours();
System.out.println("ID number is " + IDnumber);
System.out.println("Hours are " + hours);
System.out.println("Points are " + points);
Here I get the following. How do I fix this? Thanks.
ShowStudent.java:9: non-static method getIDnumber() cannot be referenced from a
static context
IDnumber = Student.getIDnumber();
^
ShowStudent.java:10: non-static method getPoints() cannot be referenced from a
static context
points = Student.getPoints();
^
ShowStudent.java:11: non-static method getHours() cannot be referenced from a s
tatic context
hours = Student.getHours();
^
3 errorsYou have to get the ID number of a particular instance i.e. IDnumber = learner.getIDnumber();
-
Non-static method getPerimeter() cannot be referenced from a static context
I am getting this error message. I assume it is because getArea( ) and getPerimeter( ) are nonstatic and main is static? Can somebody help me? Thanks in advance!
Error messages:
non-static method getArea() cannot be referenced from a static context
System.out.println("\nArea: " + onePlace.format(getArea()));
non-static method getPerimeter() cannot be referenced from a static context
System.out.println("Perimeter: " + onePlace.format(getPerimeter()));
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rectangle
public double length;
public double width;
public Rectangle()
length = 0;
width = 0;
public double getLength()
return length;
public double getWidth()
return width;
public void setLength(double length)
this.length = length;
public void setWidth(double width)
this.width = width;
public double getArea()
return (length * width);
/* public double area(Rectangle R)
double area = length * width;
return area;
public double getPerimeter()
return ((length * 2) + (width * 2));
/* public double perimeter(Rectangle R)
double perimeter = (length * 2) + (width * 2);
return perimeter;
/* public String toString()
double area = 0;
double perimeter = 0;
return "Area: " + area + "\tPerimeter: " + perimeter;
public static void main(String [] args)
DecimalFormat onePlace = new DecimalFormat("#0.0");
Rectangle R = new Rectangle();
Rectangle L = new Rectangle();
Rectangle W = new Rectangle();
Scanner input = new Scanner(System.in);
System.out.println("Enter length of rectangle: ");
L.setLength(input.nextDouble());
System.out.println("\nEnter width of rectangle: ");
W.setWidth(input.nextDouble());
System.out.println("\nArea: " + onePlace.format(getArea()));
System.out.println("Perimeter: " + onePlace.format(getPerimeter()));
// System.out.println(R.toString());
}For some reason, something isn't being read.
This is what I get:
Enter length of rectangle:
2
Enter width of rectangle:
4
Area: 0.0
Perimeter: 0.0
Press any key to continue . . .
Is it what I have to scan the input (L.setLength...)?
public static void main(String [] args)
DecimalFormat onePlace = new DecimalFormat("#0.0");
Rectangle R = new Rectangle();
Rectangle L = new Rectangle();
Rectangle W = new Rectangle();
Scanner input = new Scanner(System.in);
System.out.println("Enter length of rectangle: ");
L.setLength(input.nextDouble());
System.out.println("\nEnter width of rectangle: ");
W.setWidth(input.nextDouble());
System.out.println("\nArea: " + onePlace.format(R.getArea()));
System.out.println("Perimeter: " + onePlace.format(R.getPerimeter()));
// System.out.println(R.toString());
} -
Non-static method close() cannot be referenced from a static context
Friends,
I am having a little help with some static and not static issues.
I created a JMenuBar, it's in the file: SlideViewMenu.java
One of the operations is File->Close and another is File->Exit.
The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
Here's some of the code:
SlideViewMenu.java
public class SlideViewMenu {
public JMenuBar createMenuBar() {
final Action openAction = new OpenAction();
Action aboutAction = new AboutAction();
ActionListener menuListener = new MenuActionListener();
JMenuBar menuBar = new JMenuBar();
// All the menu stuff works fine and is taken care of here.
// Listener for Menu
class MenuActionListener implements ActionListener {
public void actionPerformed (ActionEvent actionEvent) {
String selection = (String)actionEvent.getActionCommand();
if (selection.equals("Close"))
SlideViewFrame.close();
else SlideViewFrame.exit();
}SlideView.java
// Driver class
public class SlideView {
public static void main(String[] args) {
ExitableJFrame f = new SlideViewFrame("SlideView");
// Stuff here, works fine.
// Frame class
class SlideViewFrame extends ExitableJFrame {
// some things here, work fine.
private SlideViewMenu menuBar = new SlideViewMenu();
public SlideViewFrame(String title) {
// Set title, layout, and background color
super(title);
setJMenuBar(menuBar.createMenuBar());
// Stuff here works fine.
// Handles doing stuff once the file has been selected
public void setFileName(File fullFileName, String simpleName) {
// Stuff here works fine.
// File->Close. clean up everything.
public void close() {
setTitle("SlideView");
textArea.setText("");
scrollBar.setVisible(false);
textArea.setVisible(false);
statsPanel.setVisible(false);
// File->Exit.
public void exit() {
System.exit(0);
}The error I'm getting is:
SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
I don't get it?
Thanks for all help.Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
Fortunately, there is an easy way out that ties the listener to the frame.
SlideViewMenu.java:public class SlideViewMenu
// Here's where we keep the link to the parent.
private SlideViewFrame parentFrame;
// Here's where we link to the parent.
public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
parentFrame = linkParentFrame;
final Action openAction = new OpenAction();
Action aboutAction = new AboutAction();
ActionListener menuListener = new MenuActionListener();
JMenuBar menuBar = new JMenuBar();
// All the menu stuff works fine and is taken care of here.
// Listener for Menu --- It is assumed that this is a non-static nested
// class in SlideViewMenu. All SlideViewMenu variables are accessible from
// here. If this is not the case, simply add a similar member variable
// to this class, initialize it with a constructor parameter, and
// pass the SlideViewMenu parentFrame when the listener is
// constructed.
class MenuActionListener implements ActionListener
public void actionPerformed (ActionEvent actionEvent)
String selection = (String)actionEvent.getActionCommand();
// Use parentFrame instead of class name.
if (selection.equals("Close"))
parentFrame.close();
else
parentFrame.exit();
}SlideView.java// Driver class
public class SlideView
public static void main(String[] args)
ExitableJFrame f = new SlideViewFrame("SlideView");
// Stuff here, works fine.
// Frame class
class SlideViewFrame extends ExitableJFrame
// some things here, work fine.
private SlideViewMenu menuBar = new SlideViewMenu();
public SlideViewFrame(String title)
// Set title, layout, and background color
super(title);
//Here's where we set up the link.
setJMenuBar(menuBar.createMenuBar(this));
// Stuff here works fine.
// Handles doing stuff once the file has been selected
public void setFileName(File fullFileName, String simpleName)
// Stuff here works fine.
// File->Close. clean up everything.
public void close()
setTitle("SlideView");
textArea.setText("");
scrollBar.setVisible(false);
textArea.setVisible(false);
statsPanel.setVisible(false);
// File->Exit.
public void exit()
System.exit(0);
} -
How do I identify which is static and which is non static method?
I have a question which is how can i justify which is static and which is non static method in a program? I need to explain why ? I think it the version 2 which is static. I can only said that it using using a reference. But am I correct or ?? Please advise....
if I have the following :
class Square
private double side;
public Square(double side)
{ this.side = side;
public double findAreaVersion1()
{ return side * side;
public double findAreaVersion2(Square sq)
{ return sq.side * sq.side;
public void setSide(double s)
{ side = s;
public double getSide()
{ return side;
} //class Square
Message was edited by:
SummerCoolI have a question which is how can i justify which is
static and which is non static method in a program? I
need to explain why ? I think it the version 2 which
is static. I can only said that it using using a
reference. But am I correct or ?? Please advise....If I am reading this correctly, that you think that your version 2 is a static method, then you are wrong and need to review your java textbook on static vs non-static functions and variables.
Maybe you are looking for
-
How to get values from dynamic component?
Hi: I am displaying dynamic components based on user selection, where InputText and OutputText display properly. But now i want to read that component value on button click. Can any body help me in that? Source code is as follow, text.xhtml *<code>*
-
Reorganization of Cost estimates
Dear All, Please help in knowing the difference between "Reorganization of Cost Estimates" & "Revaluation" of a product having standard price in material master. In a nutshell, why "Reorganization of Cost Estimation"(CKR1) is to be done before "Price
-
hi i successfully created a pdf file using fop in a command line. i give the xml and xsl and then automatically generates pdf. Now, i need to integrate fop with struts. i am using action but i am getting an error constructor XSLTInputHandler(String,S
-
PO (smart forms) after upgrade ERP2005
Hi, we`ve got accomplish a UG from ERP2004 to ERP2005 and to be able to do now our purchase order, created in smart forms, no more provide and not print. In SAP-Note 843193 it is described that preconfigured smart forms are available only for erp 200
-
I dowloaded the java 6 sdk beta to play around with it, however i couldnt find any resources on new features or just general info on it on suns site. all i found were how to use other tools with it, any one have a link or something to some resources