如何在加载时将.txt中的信息加载到某个Jtxtfield中

时间:2016-12-02 16:44:57

标签: java jframe jtextfield

所以我想要做的是,当我打开程序时,我之前存储的信息出现在相应的字段中。我打开程序时如何加载信息?

这是我的代码

public class Empleadofrm extends javax.swing.JFrame {

ArrayList<Empleado> arr = new ArrayList<Empleado>();
/**
 * Creates new form Empleadofrm
 */
public Empleadofrm() {
    initComponents();
    Cargar();
}

/**
 * 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();
    lblnombre = new javax.swing.JLabel();
    txtnombre = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    txtedad = new javax.swing.JTextField();
    txtsalario = new javax.swing.JTextField();
    btnatras = new javax.swing.JButton();
    btnadelante = new javax.swing.JButton();
    jLabel7 = new javax.swing.JLabel();
    cmbsexo = new javax.swing.JComboBox<String>();
    btnguardar = new javax.swing.JButton();
    btncancelar = new javax.swing.JButton();
    jLabel8 = new javax.swing.JLabel();
    btnagregar = new javax.swing.JButton();
    txtFecha = new javax.swing.JFormattedTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Nombre: ");

    jLabel2.setText("Edad: ");

    jLabel3.setText("Salario: ");

    jLabel4.setText("Fecha: ");

    btnatras.setText("<");

    btnadelante.setText(">");

    jLabel7.setText("Sexo: ");

    cmbsexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Masculino", "Femenino" }));

    btnguardar.setText("Guardar");
    btnguardar.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            btnguardarMouseClicked(evt);
        }
    });

    btncancelar.setText("Cancelar");

    jLabel8.setFont(new java.awt.Font("Microsoft Tai Le", 0, 24)); // NOI18N
    jLabel8.setText("INGRESO DE EMPLEADO");

    btnagregar.setText("Agregar");
    btnagregar.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            btnagregarMouseClicked(evt);
        }
    });

    txtFecha.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

    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(66, 66, 66)
                    .addComponent(btnguardar))
                .addGroup(layout.createSequentialGroup()
                    .addGap(44, 44, 44)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel2)
                        .addComponent(jLabel1)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel4)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtedad, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                                .addComponent(txtnombre, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtsalario))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblnombre, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(btnatras)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(btnadelante))))
                        .addComponent(jLabel8)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGap(53, 53, 53)
                            .addComponent(btnagregar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                            .addComponent(btncancelar)
                            .addGap(151, 151, 151))
                        .addComponent(cmbsexo, 0, 170, Short.MAX_VALUE)
                        .addComponent(txtFecha))))
            .addContainerGap(15, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(9, 9, 9)
            .addComponent(jLabel8)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(lblnombre)
                .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(txtedad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnatras)
                .addComponent(btnadelante))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(txtsalario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel4)
                .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel7)
                .addComponent(cmbsexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnguardar)
                .addComponent(btncancelar)
                .addComponent(btnagregar))
            .addContainerGap(81, Short.MAX_VALUE))
    );

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

private void btnagregarMouseClicked(java.awt.event.MouseEvent evt) {                                        
    // TODO add your handling code here:
    Empleado e1 = new Empleado();

    e1.setNombre(this.txtnombre.getText());
    e1.setEdad(Integer.parseInt(this.txtedad.getText()));
    e1.setSalario(Double.parseDouble(this.txtsalario.getText()));
    e1.setFecha(this.txtFecha.getText());
    e1.setSexo(this.cmbsexo.getSelectedItem().toString());

    arr.add(e1);
    JOptionPane.showMessageDialog(null,"empleado agregado");
}                                       

private void btnguardarMouseClicked(java.awt.event.MouseEvent evt) {                                        
    File f = new File("ControlEmpleados.txt");

    try{
        FileWriter fw = new FileWriter(f);
        for(Empleado e: arr){
            fw.write(e.toString());


        }

        fw.close();
    }
    catch(Exception e){}
    JOptionPane.showMessageDialog(null,"Empleados han sido guardados");


}                                       

/**
 * @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(Empleadofrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Empleadofrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Empleadofrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Empleadofrm.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 Empleadofrm().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btnadelante;
private javax.swing.JButton btnagregar;
private javax.swing.JButton btnatras;
private javax.swing.JButton btncancelar;
private javax.swing.JButton btnguardar;
private javax.swing.JComboBox<String> cmbsexo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel lblnombre;
private javax.swing.JFormattedTextField txtFecha;
private javax.swing.JTextField txtedad;
private javax.swing.JTextField txtnombre;
private javax.swing.JTextField txtsalario;
// End of variables declaration                   

private void Cargar() {

}
}

这是我的班级empleado:

public class Empleado {
private String nombre;
private int edad;
private double salario;
private String fecha;
private String sexo;

public Empleado() {
}
public Empleado(String nombre, int edad, double salario, String fecha, String sexo) {
    this.nombre = nombre;
    this.edad = edad;
    this.salario = salario;
    this.fecha = fecha;
    this.sexo = sexo;
}

public String getSexo() {
    return sexo;
}

public void setSexo(String sexo) {
    this.sexo = sexo;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public int getEdad() {
    return edad;
}

public void setEdad(int edad) {
    this.edad = edad;
}

public double getSalario() {
    return salario;
}

public void setSalario(double salario) {
    this.salario = salario;
}

public String getFecha() {
    return fecha;
}

public void setFecha(String fecha) {
    this.fecha = fecha;
}

@Override
public String toString() {
    return   nombre + "//" + edad + "//" + salario + "//" + fecha + "//" + sexo + "\r\n";
}

}

2 个答案:

答案 0 :(得分:0)

使用类似属性的内容

Properties props = new Properties();
props.setProperty("Text1", "Test");
props.store(writer, "Comment");


props.load(reader);
props.getProperty("Text1");

答案 1 :(得分:0)

您可以轻松地将数据加载到Swing应用程序中。你只需要实现一个解析器。

Application screenshot

应用

package employee;

import java.io.IOException;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class App implements Runnable {
    public static String DATA_FILE = "/resources/data.txt";

    private JFrame frame = new JFrame();
    private EmployeeForm form = new EmployeeForm();
    private EmployeeService service = new EmployeeService();

    @Override
    public void run() {
        loadData();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(form);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void loadData() {
        try {
            List<Employee> employees = service.retrieveEmployees(App.DATA_FILE);
            form.populateEmployeeList(employees);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new App());
    }
}

EmployeeForm

package employee;

import java.awt.BorderLayout;
import java.awt.Font;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;

public class EmployeeForm extends JPanel {
    private static final long serialVersionUID = 673474651649807444L;

    private JLabel employeeListLabel;
    private EmployeeListModel employeeListModel;    
    private JList<Employee> employeeList;

    public EmployeeForm() {
        super(new BorderLayout());

        createForm();
    }

    private void createForm() {
        employeeListLabel = new JLabel("Employees List");
        employeeListLabel.setFont(new Font("Arial", Font.BOLD, 18));
        this.add(employeeListLabel, BorderLayout.NORTH);

        employeeListModel = new EmployeeListModel();
        employeeList = new JList<Employee>();
        employeeList.setModel(employeeListModel);
        employeeList.setCellRenderer(new EmployeeCellRenderer());

        this.add(employeeList, BorderLayout.CENTER);
    }

    public void populateEmployeeList(List<Employee> employees) {
        employeeListModel.setEmployees(employees);
    }
}

的EmployeeService

package employee;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class EmployeeService {
    public List<Employee> retrieveEmployees(String dataFile) throws IOException {
        List<Employee> results = new ArrayList<Employee>();
        BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(dataFile)));
        String line = null;

        while ((line = br.readLine()) != null) {
            try {
                results.add(Employee.parse(line, ","));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return results;
    }
}

EmployeeListModel

package employee;

import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractListModel;

public class EmployeeListModel extends AbstractListModel<Employee> {
    private static final long serialVersionUID = 1L;
    private List<Employee> employees;

    public EmployeeListModel() {
        this(new ArrayList<Employee>());
    }

    public EmployeeListModel(List<Employee> employees) {
        this.employees = employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    @Override
    public int getSize() {
        return employees.size();
    }

    @Override
    public Employee getElementAt(int index) {
        return employees.get(index);
    }
}

EmployeeCellRenderer

package employee;

import java.awt.Component;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JLabel;
import javax.swing.JList;

public class EmployeeCellRenderer extends DefaultListCellRenderer {
    private static final long serialVersionUID = -2566924339309868945L;

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        Employee employee = (Employee) value;
        String displayText = String.format("%s, %s", employee.getName(), employee.getDateOfBirth());

        label.setText(displayText);

        return label;
    }
}

员工

package employee;

import java.text.ParseException;

public class Employee {
    private int id;
    private String name;
    private double salary;
    private String dateOfBirth;
    private String gender;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return String.format(
            "{ id: %d, name: %s, salary: $%.2f, dateOfBirth: %s, gender: %s }",
            id, name, salary, dateOfBirth, gender);
    }

    public static Employee parse(String input, String delimiter) throws ParseException, NumberFormatException {
        if (input == null || input.length() < 1 || delimiter == null) {
            throw new ParseException("Data cannot be empty!", -1);
        }

        String[] values = input.split(delimiter);

        if (values.length != 5) {
            throw new ParseException("Required data is missing!", -1);
        }

        Employee employee = new Employee();

        employee.setId(Integer.parseInt(values[0]));
        employee.setName(values[1]);
        employee.setSalary(Double.parseDouble(values[2]));
        employee.setDateOfBirth(values[3]);
        employee.setGender(values[4]);

        return employee;
    }
}

data.txt中

1,John Doe,74999.99,1956-02-12,male
2,Mary Sue,52500.00,1968-07-04,female
2,Steve Smith,63000.00,1952-10-24,male