简体   繁体   English

如何从文本文件获取正确的值到JTextField

[英]How to get correct value from text file into JTextField

I am trying to make some kind of settings in my project. 我正在尝试在项目中进行某种设置。 I have a problem with getting value from text file into JFrame. 我从文本文件获取价值到JFrame时遇到问题。 To be more specific - I have a JFrame. 更具体地说-我有一个JFrame。 From this JFrame I open another JFrame named Settings where is JTextField with value " 123 " from text file. 从这个JFrame中,我打开了另一个名为Settings JFrame,其中是文本文件中值为“ 123 ”的JTextField。 When I change the value to " 123456 " and hit the SAVE button it rewrites the text file to " 123456 " and dispose the Settings JFrame. 当我将值更改为“ 123456 ”并单击“ 保存”按钮时,它将文本文件重写为“ 123456 ”并处理Settings JFrame。 Everything is fine until now. 到目前为止一切都很好。

When I want to open the JFrame Settings again It opens it with the old value " 123 ". 当我想再次打开JFrame Settings时,它将使用旧值“ 123 ”将其打开。 But when I close both JFrames and run it again - the value in Settings JFrame is correct - " 123456 " ... I think that the text file data are loaded when I run the first JFrame and then the program remembers them and ignores the current values in text file. 但是,当我关闭两个JFrame并再次运行时- Settings JFrame中的值正确-“ 123456 ” ...我认为在运行第一个JFrame时加载了文本文件数据,然后程序记住了它们并忽略了当前文本文件中的值。 Any ideas? 有任何想法吗?

JFrame 的JFrame

package javaapplication15;

public class NewJFrame extends javax.swing.JFrame {
    Settings set = new Settings();

    public NewJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(100, 100, 100)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(167, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(93, 93, 93)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(168, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        new Settings().setVisible(true);  // TODO add your handling code here:
    }

    public static void main(String args[]) {
        //<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(
              NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(
              NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(
              NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(
              NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

Settings 设置

package javaapplication15;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Settings extends javax.swing.JFrame {
    static String text;

    public Settings() {
        initComponents();
        try {
            Scanner sc = new Scanner(new FileInputStream("settings.txt"));
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                if (line.contains("sample=")) {
                    text = line.replaceFirst("sample=", "");
                } 
            }
            sc.close();
        } catch (FileNotFoundException fnf) {
            fnf.printStackTrace();
            return;
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jTextField1.setText(text);
        jButton1.setText("save");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        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(147, 147, 147)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
            .addGap(155, 155, 155)
            .addComponent(jButton1)))
            .addContainerGap(86, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(95, 95, 95)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(41, 41, 41)
            .addComponent(jButton1)
            .addContainerGap(113, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        try {
            File file = new File("settings.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file, false);
            fw.write("sample=" + jTextField1.getText());
            fw.close();
        } catch (IOException ioe) {
            System.out.println("Nelze zapisovat.");
        }
        dispose();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* 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(
              Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(
              Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(
              Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(
              Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

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

In constructor of the Settings class , you have never initialized the text for the jTextField1 . 在Settings类的构造函数中,您从未初始化jTextField1的文本。

Initialize the jTextField1 using setText method as below : 使用setText方法初始化jTextField1,如下所示:

public Settings() {
        initComponents();
        try {
            Scanner sc = new Scanner(new FileInputStream("settings.txt"));
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                if (line.contains("sample=")) {
                    text = line.replaceFirst("sample=", "");
                } 
            }
            jTextField1.setText(text);
            sc.close();
        } catch (FileNotFoundException fnf) {
            fnf.printStackTrace();
            return;
        }
    }

I understand this is what you want , let me know if you are looking for something else. 我了解这是您想要的,如果您正在寻找其他东西,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM