Question

I want to display data from a database into JList.But its giving error that

non static variable list cannot be referenced from a static context" 
     at line "list.setModel(listModel)". 

What should I do?

Connection con=DriverManager.getConnection("jdbc:odbc:Records");
Statement st=con.createStatement();
DefaultListModel listModel=new DefaultListModel();
ResultSet rs=st.executeQuery("Select * from User_table1");
    while(rs.next()) {
      String name=rs.getString("Filename");
      listModel.addElement(name);
      System.out.println(name);
   }
list.setModel(listModel);
rs.close();
st.close();
Was it helpful?

Solution

you have 2 ways to resolve this:

  1. make this function non static
  2. make the object list static

So if you need to call this function in a static context you should use the second way. If you need this to safe the value of list for any object of this class type then you should use the first way.

And i endorse what @Andrew Thompson said in the first sentence.

OTHER TIPS

Imagine you have a blueprint. Then you produce - for example - a mobile phone from that blue print. Later you grab your scissors and cut out a part of the blueprint which is displaying an SD card and try to insert that card into your phone.

It won't work.

That is why you can't reference a non-static member from a static method. Because what I've written is true vica versa.

I suggest you read some about object oriented design. For exmaple this book is an excellent one on java. If you read through it while paying attention you will understand the root of your problem.

And by the way your compiler will tell you what is the problem and where you don't really need SO to get an answer just read the console.

As others said it before java is an object-oriented language, you are encouraged to use them so static members should be used sparingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top