The Artima Developer Community
Sponsored Link

Java Answers Forum
reference to non-static variable from a static context..problems!

10 replies on 1 page. Most recent reply: Mar 27, 2004 9:44 AM by twc

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 10 replies on 1 page
Guest
reference to non-static variable from a static context..problems! Posted: Mar 25, 2004 4:37 PM
Reply to this message Reply
Advertisement
<pre>So here i am, making a program and i seem to have
stumbled across a problem. Blame it on my lack of Java
knowledge, which is perfectly fine cuz i'm still a very
very beginner..and don't understand basic concepts
properly well still. well anyways, here's how it goes.

basically this program is a diary program. (simple enough)
there is a JtabbedPane used to have two menus, one side is changing the user, the other side is the actual diary.
(so i have two separate files called User.java and
Diary.java). well the problem arrises that i'm trying to use a non-static variable from the User.Java side in the Diary.Java side...


in the User selection menu, i used a JList...
and using list.getSelectedValue() , i tried to assign to a String variable userName like this below:

//This is declared in the beginning of the class User.java:


<java>
public String userName = "Default";
</java>


//i had to do this or else a nullpointer error occurs



// This is part of a button action.. this action takes place after the user selects a name and presses OK button


<java>
class OkListener implements ActionListener {
public void actionPerformed(ActionEvent e) {

getUserName(userName);

}
}

public String getUserName(String userName) {
userName = (String)(usersList.getSelectedValue());

JFrame frame = new JFrame();
String message = "The Following User has been" +
"Selected: " + userName;
JOptionPane.showMessageDialog(frame, message);

return userName;
}
</java>


simple enough right? but the problem arises that i'm trying to use this variable on the other tab, Diary.java
a part saying:


<java>
public JLabel diaryUserLabel = new JLabel("Diary ("+ User.userName + ")",JLabel.CENTER);
</java>


when i try to compile this i get a message saying that i'm
trying to reference a non-static variable from a static context.


i'm wondering how i can solve this, i understand basically the problem is that i'm trying to get a variable the could change from one side to another when that's not possible..
but i dunno how i can get around this probelm..


can anyone explain? pleaz? also, if u need more clarifications on this, plese post a message, i'll gladly add more information if it can help u solve my problm!
</pre>


twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: reference to non-static variable from a static context..problems! Posted: Mar 25, 2004 8:11 PM
Reply to this message Reply
Your basic problem is that you don't yet understand the difference between instance (non-static) and a class (static) variables. This is not an unusual error for beginners. I'm not sure my explanations are going to make sense until you learn the difference, but I'll try.

userName is declared as an instance variable since your declaration doesn't include the keyword static. That is how is should be declared. DON'T make it static!!!!!

The problem is that in the other class, where you have User.userName, you are calling the variable from the class instead of an object of that class. Somewhere in your code you need something like the following to create a User object.
User someUser = new User();

This means that your line would become
public JLabel diaryUserLabel = new JLabel("Diary ("+ someUser.userName + ")",JLabel.CENTER);

Actually, this isn't ideal either. A better approach will have the userName variable private instead of public and you would use the getUserName() method instead of accessing the variable directly.
public JLabel diaryUserLabel = new JLabel("Diary ("+ someUser.getUserName() + ")",JLabel.CENTER);

The big question is where does this all need to go? Without knowing more about your code, I'm not sure. Where is the button? In the User class, the Diary class, or some third class? Without knowing that, it is hard to be more specific. If you post more info, I can be more helpful.

Guest
Re: reference to non-static variable from a static context..problems! Posted: Mar 26, 2004 2:06 AM
Reply to this message Reply
-----------------------------------------------------
hello, thanx for your reply!
I am posting a bit more so that i could perhaps get more help that i need.
it makes sense what u are talking about, trying to access a variable from a class instead of an object
one of the things u suggested was declaring an object inside the Diary class like this:

User someUser = new User();

well actually , i've already tried that. but it didn't work either.

I have a line saying

User userData = new User();
and then for the label i tried userData.userName
but i realized the problem for this was the same...
it still says that i'm referring to a non-static variable..

the button exists in the diary class, which is what i guess is causing a problem... i hope this reply cleard things up abit. plz~ more help :D

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: reference to non-static variable from a static context..problems! Posted: Mar 26, 2004 6:08 AM
Reply to this message Reply
> User userData = new User();
> and then for the label i tried userData.userName
> but i realized the problem for this was the same...
> it still says that i'm referring to a non-static
> variable..

Without seeing more of your code, I can't tell what the problem is. Just having this line in the code is not enough. It also has to be in the right place.

> the button exists in the diary class, which is what i
> guess is causing a problem... i hope this reply cleard
> things up abit. plz~ more help :D

If the button is in the Diary class, then you almost certainly need an instance of the User class in the Diary class too. Again, it is impossible to help without seeing more code.

Again, the real problem is that you clearly do not understand what difference between static (class) and non-static (instance) variables. If you have a book, the explanation should be in there somewhere. You need to focus on that. In the meantime, post more code!

Guest
Re: reference to non-static variable from a static context..problems! Posted: Mar 26, 2004 6:35 AM
Reply to this message Reply
here are the codes,
the java file called Diary that i've been referring to is actually called GUI.java, which canbe seen below

there are 2 more JAVA files, which are called Digital.java and Diary.java (this is the one called diary.java, but not relavant to what we've been discussing about in this thread).
digital.java contanis the JtabbedPane , the one containing the main.
diary.java is one that controls saving and raeding files and creating calendar screens.. but i found them irralevent to post, so here are the two important ones that is causing the problem

-------------------------------------------------------
THIS IS THE FILE USER.JAVA
------------------------------------------------------


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.text.Collator;









public class User extends JPanel implements ListSelectionListener {

public JList usersList;
private DefaultListModel usersModel;

public String userName = new String("Default");
private JButton deleteButton = new JButton("Delete");
private JTextField nameField;
private JButton addButton = new JButton("Add") ;
private JButton okButton = new JButton("OK");
private JLabel selectNote =new JLabel("Please select the user name!",JLabel.CENTER);
int i = 1; //this "i" variable will be used in the sortUser method



private GUI guiData;

public User() {


usersModel = new DefaultListModel();
usersModel.addElement("Default");

//Create the list and put it in a scroll pane.
usersList = new JList(usersModel);
usersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
usersList.setSelectedIndex(0);
usersList.addListSelectionListener(this);
usersList.setVisibleRowCount(5);
usersList.setPreferredSize(new Dimension(200, 200));

JScrollPane usersListScrollPane = new JScrollPane(usersList);



AddListener addListener = new AddListener(addButton);
addButton.addActionListener(addListener);
addButton.setEnabled(false);

deleteButton.addActionListener(new DeleteListener());

okButton.addActionListener(new OkListener());

nameField = new JTextField(10);
nameField.addActionListener(addListener);
nameField.getDocument().addDocumentListener(addListener);
String name = usersModel.getElementAt(
usersList.getSelectedIndex()).toString();


//Create a panel that uses BoxLayout.
JPanel mainpanel = new JPanel();
mainpanel.setLayout(new BorderLayout());

JPanel topPanel = new JPanel();
topPanel.add(new Label("USER SELECTION SCREEN"));

JPanel menuPanel = new JPanel(new GridLayout(2, 3));
menuPanel.add(nameField);
menuPanel.add(addButton);
menuPanel.add(deleteButton);
menuPanel.add(selectNote);
menuPanel.add(okButton);


mainpanel.add(topPanel, BorderLayout.NORTH);
mainpanel.add(usersListScrollPane, BorderLayout.CENTER);
mainpanel.add(menuPanel, BorderLayout.SOUTH);

add(mainpanel);

userName = userName;

}

class DeleteListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//This method can be called only if
//there's a valid selection
//so go ahead and remove whatever's selected.
int index = usersList.getSelectedIndex();
usersModel.remove(index);

int size = usersModel.getSize();

if (size == 0) { //Nobody's left, disable "delete".
deleteButton.setEnabled(false);

}
else { //Select an index.
if (index == usersModel.getSize()) {
//removed item in last position
index--;
}

usersList.setSelectedIndex(index);
usersList.ensureIndexIsVisible(index);
}
}
}

class OkListener implements ActionListener {
public void actionPerformed(ActionEvent e) {

userName = (String)(usersList.getSelectedValue());

JFrame frame = new JFrame();
String message = "The Following User has been Selected: " + userName;
JOptionPane.showMessageDialog(frame, message);


}
}


class AddListener implements ActionListener, DocumentListener {
private boolean alreadyEnabled = false;
private JButton button;

public AddListener(JButton button) {
this.button = button;
}

//Required by ActionListener.
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();

if (name.length()>8) {
Toolkit.getDefaultToolkit().beep();
nameField.requestFocusInWindow();
nameField.selectAll();
JFrame frame = new JFrame();
String message = "Please make the name below 8 Letters";
JOptionPane.showMessageDialog(frame, message);
return;
};


//User didn't type in a unique name...
if (name.equals("") || alreadyInList(name)) {
Toolkit.getDefaultToolkit().beep();
nameField.requestFocusInWindow();
nameField.selectAll();
JFrame frame = new JFrame();
String message = "This User Already Exists";
JOptionPane.showMessageDialog(frame, message);
//shows a message if the user is already in the list
return;
}

int index = usersList.getSelectedIndex(); //get selected index
if (index == -1) { //no selection, so insert at beginning
index = 0;
} else { //add after the selected item
index++;
}

usersModel.insertElementAt(nameField.getText(), index);
//If we just wanted to add to the end, we'd do this:
//usersModel.addElement(employeeName.getText());

//Reset the text field.
nameField.requestFocusInWindow();
nameField.setText("");

//Select the new item and make it visible.
usersList.setSelectedIndex(index);
usersList.ensureIndexIsVisible(index);


sortUsers(); //view below for the "sortUser()" method
}


protected boolean alreadyInList(String name) {
return usersModel.contains(name);
}

//Required by DocumentListener.
public void insertUpdate(DocumentEvent e) {
enableButton();
}

//Required by DocumentListener.
public void removeUpdate(DocumentEvent e) {
handleEmptyTextField(e);
}

//Controls whether the Add Button should be enabled or not
public void changedUpdate(DocumentEvent e) {
if (!handleEmptyTextField(e)) {
enableButton();
}
}

private void enableButton() {
if (!alreadyEnabled) {
button.setEnabled(true);
}
}

private boolean handleEmptyTextField(DocumentEvent e) {
if (e.getDocument().getLength() <= 0) {
button.setEnabled(false);
alreadyEnabled = false;
return true;
}
return false;
}
}



public void sortUsers() {

usersModel = (DefaultListModel) usersList.getModel();
int numItems = usersModel.getSize();
String[] a = new String[numItems];
for (int i=0;i<numItems;i++){
a = (String)usersModel.getElementAt(i);
}
sortArray(Collator.getInstance(),a);
for (int i=0;i<numItems;i++) {
usersModel.setElementAt(a, i);
}
}

public void sortArray(Collator collator, String[] strArray) {
String tmp; if (strArray.length == 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if( collator.compare(strArray, strArray[j] ) > 0 ) {
tmp = strArray;
strArray = strArray[j];
strArray[j] = tmp;
}
}
}
}




//This method is required by ListSelectionListener.
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {

if (usersList.getSelectedIndex() == -1) {
//No selection, disable delete button.
deleteButton.setEnabled(false);

} else {
//Selection, enable the delete button.
deleteButton.setEnabled(true);
}
}
}



}










-----------------------------------------------------
THIS IS THE FILE: GUI.JAVA
------------------------------------------------------



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*; //imports the required tools to use the program in a Graphical User Interface.

public class GUI extends JPanel {

User userData = new User();
private Diary data; //instantiates objects of other classes


//declares all the components that will be used the GUI

private JTextArea output = new JTextArea(20, 30);
private int year, month, day, daysinmonth;
private JLabel yearLabel = new JLabel("", JLabel.CENTER);
private JLabel monthLabel = new JLabel("", JLabel.CENTER);
private JLabel notice = new JLabel("Please save your diary entry!", JLabel.CENTER);
public JLabel diaryUserLabel = new JLabel("Diary ("+ userData.userName + ")",JLabel.CENTER);
private JButton nextMonth = new JButton(">");
private JButton previousMonth = new JButton("<");
private JButton nextYear = new JButton(">");
private JButton previousYear = new JButton("<");
private JButton[] dayButton = new JButton[31];
private JButton save = new JButton("Save");
private static final String[] nameofmonth = new String[] {
"January", "Febuary", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};




public GUI() {
data = new Diary();
for (int i=0; i<dayButton.length; i++) {
dayButton = new JButton(""+(i+1));
} //creates buttons for the dates
fillout(); //fills in the buttons. see below to see how fillout function works

final int width = 800, height = 600;
setSize(width,height); //sets the size of the program screen





//assigns action to the buttons created.
ButtonListenerSave savel = new ButtonListenerSave();
save.addActionListener(savel);
ButtonListenerYear yearl = new ButtonListenerYear();
nextYear.addActionListener(yearl);
previousYear.addActionListener(yearl);
ButtonListenerMonth monthl = new ButtonListenerMonth();
nextMonth.addActionListener(monthl);
previousMonth.addActionListener(monthl);
ButtonListenerDay dayl = new ButtonListenerDay();
for (int i=0; i<dayButton.length; i++) {
dayButton.addActionListener(dayl);
}

// Let the user change the output.
output.setEditable(true);


// Place the list and input line in a panel.

JPanel contents = new JPanel();
contents.setLayout(new BorderLayout());

contents.add(diaryUserLabel, "North"); //add the heading "Diary (userName)"


JPanel mainpanel = new JPanel();
mainpanel.setLayout(new BorderLayout()); //the main panel is created

JPanel subpanel = new JPanel(); //a subpanel including the year,month is created
subpanel.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,3)); //makes panel1 into a grid of 2 by 3
panel1.add(previousYear); //
panel1.add(yearLabel); //
panel1.add(nextYear); //
panel1.add(previousMonth);// adds button& label that will change year,month
panel1.add(monthLabel); //
panel1.add(nextMonth); //
subpanel.add(panel1, "North"); //panel1 is added to the top of the subpanel

JPanel panel2 = new JPanel();
GridLayout layout = new GridLayout(5,7); //makes panel2 which is of grid 5 by 7
panel2.setLayout(layout);
for (int i=0; i<daysinmonth; i++) {
panel2.add(dayButton); //adds the day buttons into the grid.
}
subpanel.add(panel2, "Center");
mainpanel.add(subpanel, "West"); //the subpanel is added to mainPanel

JPanel panel3 = new JPanel(); //makes panel 3
panel3.setLayout(new BorderLayout());
panel3.add(notice, "North");
panel3.add(save, "Center"); // notice and save button added to the panel3
mainpanel.add(panel3, "South"); //panel 3 added to mainpanel

mainpanel.add(new JScrollPane(output), "East");

contents.add(mainpanel, "Center");
add(contents);
}

public void fillout () {
ArrayList A = data.getText();
output.setText("");
for (int i=0; i<A.size(); i++) {
output.append(A.get(i).toString()+"\n");
}
day = data.getDateInfo()[0];
month = data.getDateInfo()[1];
year = data.getDateInfo()[2];
daysinmonth = data.getDateInfo()[3];
//receives the information about day month and year from data.getdateinfo
monthLabel.setText(nameofmonth[month-1]);
//using the month information, refer to array namefmonth to assign a label
yearLabel.setText(""+year);
for (int i=0; i<dayButton.length; i++) {
boolean bool = (i<daysinmonth)? true: false;
dayButton.setVisible(bool);
// controls visibility of day buttons. for example,
// in april, the day button for 31 will not appear
dayButton.setBackground(save.getBackground());
}
dayButton[day-1].setBackground(new Color(0,0,255));

}

// The descriptions of action that is assigned to the buttons above.
private class ButtonListenerDay implements ActionListener {
public void actionPerformed(ActionEvent evt) {
day = Integer.parseInt(evt.getActionCommand());
data = new Diary(day, month, year);
fillout();
//the day will be changed,
//and then the new values will be assigend to data. Then fillout again
}
}

private class ButtonListenerMonth implements ActionListener {
public void actionPerformed(ActionEvent evt) {
month = (evt.getActionCommand().equalsIgnoreCase("<"))? month-1: month+1;
data = new Diary(1, month, year);
fillout(); //similar to ButtonListenerDay, but month changed.
}
}

private class ButtonListenerYear implements ActionListener {
public void actionPerformed(ActionEvent evt) {
year = (evt.getActionCommand().equalsIgnoreCase("<"))? year-1: year+1;
data = new Diary(1, month, year);
fillout(); //similar to ButtonListenerDay, but year changed
}
}

private class ButtonListenerSave implements ActionListener {
public void actionPerformed(ActionEvent evt) {
ArrayList A = new ArrayList();
StringTokenizer st = new StringTokenizer(output.getText(), "\n");
while (st.hasMoreTokens()) {
A.add(st.nextToken());
}
data.setText(A);
data = new Diary(day, month, year);
fillout(); //saves the diary entry to the file.
}
}
}

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: reference to non-static variable from a static context..problems! Posted: Mar 26, 2004 9:22 AM
Reply to this message Reply
I pasted your code into my editor and tried to compile them. I got a ton of other errors where you have String and String[] mixed up, JButton and JButton[] mixed up, and a couple dealing with the fact that I didn't have the Diary.java class. But the lines that you have been asking about did not get flagged. They look like they should work to me. I don't see why you are getting that particular error.

It is possible that the other errors are confusing the compiler by throwing it off a line or two. I've seen that happen before. Try fixing all of the other errors and the one that you have been writing about may vanish!

It is also possible that my compiler just found so many errors that it couldn't get to that one.

On a side note, your instance variables, like userName, normally should be private. Then you access them with accessor methods (commonly called get methods). I wouldn't mess with that, however, until you get the other problems fixed.

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: reference to non-static variable from a static context..problems! Posted: Mar 26, 2004 12:51 PM
Reply to this message Reply
Just for the heck of it, I tried an experiment. I deleted everything from User.java and GUI.java except the lines in question. Like this ...
public class User
{
    public String userName = new String("Default");
}
and this ...
import javax.swing.*;
public class GUI
{
    User userData = new User();
    public JLabel diaryUserLabel = new JLabel("Diary ("+ userData.userName + ")", JLabel.CENTER);
}


It compiled fine. The problem isn't with those lines. Fix the other errors that I mentioned and you should be OK.

mausam

Posts: 243
Nickname: mausam
Registered: Sep, 2003

Re: reference to non-static variable from a static context..problems! Posted: Mar 27, 2004 4:50 AM
Reply to this message Reply
I think this [Sun-Ho Kim ]is the same idiot with the msg assholes in the other thread.

Guest
Re: reference to non-static variable from a static context..problems! Posted: Mar 27, 2004 6:25 AM
Reply to this message Reply
yeah that was with my account, but it wasn't me, my friend posted that while i was gone helping some other student with their Powerpoint presentation.
i wouldn't post that if i was asking for help like this!

Guest
Re: reference to non-static variable from a static context..problems! Posted: Mar 27, 2004 6:34 AM
Reply to this message Reply
i see what u mean, but that's because the string userName is first defined as "Default"...
so it works fine.

but if u see the code above, i made it so that this userName changes according to the name selected in the JList.

but if i do that, the one in the GUI.Java class doesn't change the name. so it still appears as "Default"..

if u could tell me ur email address i'll send u all my code files. I tried sending an email to the one shown in ur details but that email didn't seem to work..
thnx

twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: reference to non-static variable from a static context..problems! Posted: Mar 27, 2004 9:44 AM
Reply to this message Reply
> if u could tell me ur email address i'll send u all my
> code files. I tried sending an email to the one shown in
> ur details but that email didn't seem to work..
> thnx

Try again. It is an account that I use for internet postings like this. All of the spammers see it instead of my "real" account. I hadn't cleaned it out for a few weeks and it was over the storage limit.

Flat View: This topic has 10 replies on 1 page
Topic: convert an int to a byte array Previous Topic   Next Topic Topic: Easy Way to Develop JAVA Enterprise Applications

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use