why this code is not working?,

error: non-static variable jTextField1 cannot be referenced from a static context

try{
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/sample", "", "");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT name FROM testtable");
            
            while (rs.next()){
                String n = rs.getString("name");               
                jTextField1.setText(n);
                 }            
            stmt.close();
            con.close();                  
            
        }catch(Exception e){

Probably because the variable jTextField1 is not static and the method where you put that code is static: This is wrong:

class A {
  private int a = 5; // non static variable

  private static void method() {
     System.out.println(a);
  }
}

The method is static, so you cannot use the non-static variable.
There are 2 good solutions:
Make the method non-static:

class A {
  private int a = 5; // non static variable

  private void method() {
     System.out.println(a);
  }
}

Leave it static and add an argument to the method and then call it with that argument

class A {
  private int a = 5; // non static variable

  private static void print(int i) {
     System.out.println(i);
  }


  // calling the method from somewhere else:
  {
    print(a);

  }
}

ahh.. i see.. still can't do it.

is there anyway that I can use netbeans act like visual studio?,
i mean as easy as visual studio, because I don't think I can display data on textfields directly, unlikely in visual studio

ahh.. i see.. still can't do it.

is there anyway that I can use netbeans act like visual studio?,
i mean as easy as visual studio, because I don't think I can display data on textfields directly, unlikely in visual studio

What have you tried? Is jTextField1 static or not. It shouldn't be static. The gui builder has nothing to do with the error. You write the code for executing the query.

I am not sure. But you can try it....

String SQL = "SELECT * FROM sample "; 
Statement stmt =  con.createStatement();
 stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);
 jTextField1.setText(rs.getString(String.valueOf("column name from SQL table")));
commented: Useless advice. Has nothing to do with the real problem -3

I think there is something wrong in your code(line-7).
I will try to solve.
Thank you.

jTextField1.setText(rs.getString(String.valueOf("column name from SQL table")));

That is not going to solve the problem. It is exactly the same with the code aldeene posted.

aldeene - If you haven't solved your problem you can post some more of your code

Can you post your full code aldeene?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.