如何在非静态 jtextField 中输出字符串?

how to output a string in non-static jtextField?

我是 java 的新手,想将我的文本文件输出到 java gui 中的 textfield/textarea 我首先将整个文件读入一个字符串(文件不大) 然后当我尝试 setText() 时。我得到非静态...错误; 我搜索了一下,但没有得到任何结果; 整个代码是:

/*
 * 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);

错误是“无法从静态上下文中引用非静态变量 jTextField1” 我还想将一个字符串设置为一个 jlabel; 每次我 运行 程序时我的字符串都会改变(包括随机数) 但由于同样的问题,我又无法输出;

如果我的问题不合适或重复,请告诉我将其删除。 此致,

您必须将 jTextField1 定义为非静态的,即可以从非静态方法访问,并且我假设上面的代码驻留在静态的 main 方法中,因此使用 static 关键字定义 testfield,即在 class 级别并从main 方法就像你正在做的那样。

private static JTextField jTextField1 = ...

在您的 DisplayFile class 中创建一个方法,名称类似于 setText,它接受一个 String 参数。

public void setText(String text) {

在此方法中,使用传递给该方法的值设置文本字段的文本。

jTextField1.setText(text);

创建 DisplayFile class 的实例后,将文件读入 String,然后调用 setText 方法,将此 String 对它的价值...

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

DisplayFile displayFile = new DisplayFile();
displayFile.setText(entireFileContents);
displayFile.setVisible(true);

修改main方法,去掉Scanner代码,留下

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

并提供一个新的setter来扫描文件

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;
}