0

I'm new to java and want to output my text file into a textfield/textarea in java gui I first read my whole file into one string (file is not big) then when I try to setText() it . i get non-static ... error; I searched about it but didn't get any results; the whole code is :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package project;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JTextArea;

/**
 *
 * @author qp
 */
public class DisplayFile extends javax.swing.JFrame  {


    /**
     * Creates new form DisplayFile
     */
    public DisplayFile() {
        initComponents();
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Your exam file content is : ");

        jTextField1.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(166, 166, 166)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(242, 242, 242)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(175, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(61, 61, 61)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(260, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws FileNotFoundException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DisplayFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DisplayFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DisplayFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DisplayFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        String entireFileText = null;
         entireFileText = new Scanner(new File("D:/exam.txt"))
        .useDelimiter("\\A").next();
        jTextField1.setText(entireFileText);

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DisplayFile().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}


// i get the error here :



 String entireFileText = null;
             entireFileText = new Scanner(new File("D:/exam.txt"))
            .useDelimiter("\\A").next();
            jTextField1.setText(entireFileText);

the error is " non static variable jTextField1 cannot be referenced to from a static context" I also would like to set a string to a jlabel; my string changes every time I run the program (includes random numbers) but again I can't output that because of the same problem;

if my question is inappropriate or duplicate tell me to delete it. Regards,

Sindhoo Oad
  • 1,194
  • 2
  • 13
  • 29
  • 2
    Please post all the relevant code as well as the exact error message. – shree.pat18 Jan 27 '15 at 09:21
  • What you may have is: the two statements in a static method (please add the header of the method) and variable `entireFileText` is a regular class field. Add `static` to the variable declaration. – laune Jan 27 '15 at 09:24
  • 1
    possible duplicate of [non-static variable cannot be referenced from a static context](http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – Oleg Estekhin Jan 27 '15 at 10:58

3 Answers3

0

You must have defined jTextField1 as non static i.e. accessible from non static methods and i presume code above resides in main method which is static, so define testfield with static keyword i.e. at class level and access it from main method just like you are doing.

private static JTextField jTextField1 = ...
SMA
  • 36,381
  • 8
  • 49
  • 73
  • 1
    No, no and no! Making a UI component static is never the right answer (in fact using static fields is just generally a bad idea). What happens when the op creates another instance of the frame? This is just generating bad habits and we've seeing way to many examples of this on questions which wouldn't have had problems otherwise. The OP should either pass the String to the class via a setter or load the file within the class itself (personally, I prefer the first) – MadProgrammer Jan 27 '15 at 09:49
0

Create a method in your DisplayFile class, called something like setText, which takes a String parameter.

public void setText(String text) {

Within this method, set the text of the text field with the value passed to the method.

jTextField1.setText(text);

After you have created an instance of the DisplayFile class, read your file into a String and then call the setText method, passing this String value to it...

String  entireFileContents = new Scanner(new File("D:/exam.txt")).useDelimiter("\\A").next();

DisplayFile displayFile = new DisplayFile();
displayFile.setText(entireFileContents);
displayFile.setVisible(true);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Modify the main method, removing the Scanner code , leaving

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new DisplayFile().setText(new File("exam")).setVisible(true);
        }
    });
}

and provide a new setter to scan the file

DisplayFile setText(File file) {
    String entireFileText = null;
    try {
        entireFileText = new Scanner(file)
           .useDelimiter("\\A").next();
    } catch (FileNotFoundException e) {
         //Error handling
         e.printStackTrace();
    }
    jTextField1.setText(entireFileText);
    return this;
}
Neil Masson
  • 2,609
  • 1
  • 15
  • 23