如何将数据从我的TXT文件获取到JTtable

how can i get data from my txt file to the jtable

提问人:Metrix L 提问时间:11/13/2023 最后编辑:aledMetrix L 更新时间:11/13/2023 访问量:50

问:

这是我创建的类,用于将数据从文本文件加载到表中。这样我就可以删除、更新和注册用户。唯一不起作用的是表格不显示用户。

这是我创建的类

package Classes;

import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;


public class RegistrationUsers 
{
    private List<Users> users;
    private String usersFilePath;
    
    public class Users
    {
        private String name;
        private String email;
        private String contact;
        private String password;
        private String userType;
        
        public Users(String name, String email, String contact, String password, String userType)
        {
            this.name = name;
            this.email = email;
            this.contact = contact;
            this.password = password;
            this.userType = userType;
        }

        public String getName() 
        {
            return name;
        }

        public String getEmail() 
        {
            return email;
        }

        public String getContact() 
        {
            return contact;
        }

        public String getPassword() 
        {
            return password;
        }

        public String getUserType() 
        {
            return userType;
        }
    }
    
    public RegistrationUsers(String filePath)
    {
        users = new ArrayList<>();
        usersFilePath = filePath;
        loadUsers();
    }
    
    public void registerUser(Users user)
    {
        users.add(user);
        saveUsers();
    }
    
    public void updateUser(Users user)
    {
        for(int i = 0; i < users.size(); i++)
        {
            if(users.get(i).getEmail().equals(user.getEmail()))
            {
                users.set(i, user);
                saveUsers();
                return;
            }
        }
    }
    
    public void deleteUser(Users user)
    {
        users.remove(user);
        saveUsers();
    }
    
    public List<Users> getUsers()
    {
        System.out.println("Returning users: " + users.size());
        return users;
    }
    
    private void loadUsers()
    {
        String filePath = "C:/APU/Year 2/SEMESTER 1/Assignments/Object Oriented Development with Java/University Food Ordering System/Users.txt";
        System.out.println("Loading users from file: " + filePath);
        
        users.clear();
        
        try(BufferedReader re = new BufferedReader(new FileReader(filePath)))
        {
            String line;
            int lineNumber = 0;
            
            while((line = re.readLine()) != null)
            {
                lineNumber++;
                System.out.println("Line read: " + line);
                
                String[] parts = line.split(":");
                System.out.println("Parts: " + Arrays.toString(parts));
                if(parts.length == 5)
                {
                    Users user = new Users(parts[0], parts[1], parts[2], parts[3], parts[4]);
                    users.add(user);
                }
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        System.out.println("Number of users loaded: " + users.size());
        System.out.println("Returning users: " + users);
    }
    
    private void saveUsers()
    {
        try(BufferedWriter wr = new BufferedWriter(new FileWriter("C:/APU/Year 2/SEMESTER 1/Assignments/Object Oriented Development with Java/University Food Ordering System/Users.txt", true)))
        {
            Users user = users.get(users.size() - 1);
            wr.newLine();
            wr.write("Name:" + user.getName());
            wr.newLine();
            wr.write("Email:" + user.getEmail());
            wr.newLine();
            wr.write("Contact:" + user.getContact());
            wr.newLine();
            wr.write("Password:" + user.getPassword());
            wr.newLine();
            wr.write("Role:" + user.getUserType());
            wr.newLine();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}`

这是我的管理员 jframe 中的代码

`package JFrames;

import Classes.RegistrationUsers;
import Classes.RegistrationUsers.Users;
import Classes.UpdateProfile;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class Admin extends javax.swing.JFrame 
{ 
    private final UpdateProfile updateProfile;
    private DefaultTableModel model = new DefaultTableModel();
    private String columns[] = {"Name", "Email", "Contact", "Password", "UserType"};
    private final RegistrationUsers registrationUsers;
    
        
    public Admin(String email, String password)
    {
        initComponents();
            
        updateProfile = new UpdateProfile(email, password, txtEmail, txtName, txtContact, txtPassword);  
        
        registrationUsers = new RegistrationUsers("C:/APU/Year 2/SEMESTER 1/Assignments/Object Oriented Development with Java/University Food Ordering System/Users.txt");
        
        model.setColumnIdentifiers(columns);
        loadUsersToTable();
    }   
    
    private void loadUsersToTable()
    {
        List<Users> usersList = registrationUsers.getUsers();
        System.out.println("Number of users in usersList: " + usersList.size());
        for(Users user : usersList)
        {
            String[] userData = {user.getName(), user.getEmail(), user.getContact(), user.getPassword(), user.getUserType()};
            model.addRow(userData);
        }
        InfojTable.setModel(model);
    }
    private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {                                            
        String name = txtName1.getText();
        String email = txtEmail1.getText();
        String contact = txtContact1.getText();
        String password = txtPassword1.getText();
        String userType = cmbUserType.getSelectedItem().toString();
        
        if(name.isBlank() || email.isBlank() || contact.isEmpty() || password.isEmpty() || userType.isEmpty())
        {
            JOptionPane.showMessageDialog(this,"Please Fill all the Requirments", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        RegistrationUsers reU = new RegistrationUsers("C:/APU/Year 2/SEMESTER 1/Assignments/Object Oriented Development with Java/University Food Ordering System/Users.txt");
        RegistrationUsers.Users user = reU.new Users(name, email, contact, password, userType);
        
        reU.registerUser(user);
        
        JOptionPane.showMessageDialog(this,"User Registered successfully."); 
        
        String register[] = {name, email, contact, password, userType};
        model.addRow(register);
    }                                           

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        txtName1.setText("");
        txtEmail1.setText("");
        txtContact1.setText("");
        txtPassword1.setText("");
        
        cmbUserType.setSelectedIndex(0);
        
    }                                        

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
        DefaultTableModel model2 = (DefaultTableModel)InfojTable.getModel();
        
        int selectedRow = InfojTable.getSelectedRow();
        
        if(selectedRow == -1)
        {
            JOptionPane.showMessageDialog(this, "Please select a user to delete.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String emailToDelete = model2.getValueAt(selectedRow, 1).toString();
        
        RegistrationUsers.Users userToDelete = registrationUsers.getUsers().stream()
            .filter(user -> user.getEmail().equals(emailToDelete)).findFirst().orElse(null);
        
        if(userToDelete != null)
        {
            registrationUsers.deleteUser(userToDelete);
            model2.removeRow(selectedRow);
            JOptionPane.showMessageDialog(this, "User deleted successfully.");            
        }
        else
        {
            JOptionPane.showMessageDialog(this, "User not found", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }                                         

    private void InfojTableMouseClicked(java.awt.event.MouseEvent evt) {                                        
       DefaultTableModel model1 = (DefaultTableModel)InfojTable.getModel();
       
       String Name = model1.getValueAt(InfojTable.getSelectedRow(), 0).toString();
       String Email = model1.getValueAt(InfojTable.getSelectedRow(), 1).toString();
       String Contact = model1.getValueAt(InfojTable.getSelectedRow(), 2).toString();
       String Password = model1.getValueAt(InfojTable.getSelectedRow(), 3).toString();
       String UserType = model1.getValueAt(InfojTable.getSelectedRow(), 4).toString();
       
       txtName1.setText(Name);
       txtEmail1.setText(Email);
       txtContact1.setText(Contact);
       txtPassword1.setText(Password);
       cmbUserType.setSelectedItem(UserType);
    } 

我试图将数据从文本文件获取到 jtable,但我没有得到任何东西,当我注册用户时,它显示在表中。我想做的是,当我登录时,我想转到注册页面并查看jtable中的用户。

java oop netbeans

评论

0赞 aled 11/13/2023
请避免使用格式来使您的问题更引人注目。根据以下指南,还要避免在您的问题中使用称呼/感谢:stackoverflow.com/help/behavior
0赞 Hovercraft Full Of Eels 11/13/2023
首先,最好进行一些调试,然后在问题中显示调试尝试的结果。
0赞 Hovercraft Full Of Eels 11/13/2023
如果您不确定如何执行此操作,请查看什么是调试器以及它如何帮助我诊断问题?以及如何调试小程序链接。他们不会解决实际问题,但可以为您提供帮助您解决问题的步骤,或者帮助您更加关注问题,从而帮助您改进这个问题。
0赞 camickr 11/13/2023
好吧,您有显示列表中用户数的调试代码。我猜是0。以一种格式写出数据,但尝试以另一种格式读取数据。
0赞 camickr 11/13/2023
另外,请注意,数据位于两个位置:1) 您的用户列表 2) TableModel。这意味着您现在将无法保持数据同步。更好的解决方案是创建自定义 TableModel 来保存用户数据。然后,您只需要更新模型即可。List 将成为 TableModel 的一部分。请参阅:行表模型中的示例,了解如何创建自定义模型。

答: 暂无答案