编辑JTable行

时间:2013-02-22 10:33:40

标签: java swing file-io jtable abstracttablemodel

我使用JTable来显示用户信息。 我添加了一个编辑按钮,当用户选择一行并单击该按钮时,所选行必须编辑并重写为文件。

应该怎么做?

public class AllUser extends AbstractTableModel {

UserInformation uiS = new UserInformation();
String[] col = {"ID", "Fname", "Lname", "Gender", "Date"};
List<UserInformation> Udata = new ArrayList<UserInformation>();

public AllUser() {
    BufferedReader br = null;
    try {
        FileReader fr = new FileReader("AllUserRecords.txt");
        br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().length() == 0) {
                continue;
            }
            Udata.add(initializeUserInfos(line));
        }
    } catch (IOException e) {
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ioe) {
            }
        }
    }
}

private UserInformation initializeUserInfos(String str) {
    UserInformation Uinit = new UserInformation();
    String[] CellArray = str.split("     ");
    Uinit.setID(CellArray[0]);
    Uinit.setFname(CellArray[1]);
    Uinit.setLname(CellArray[2]);
    Uinit.setGender(CellArray[3]);
    Uinit.setDate(CellArray[4]);
    return Uinit;
}

public void RemoveRow(int rowIndex) {
    if (RemoveUserFromFile(rowIndex)) {
        Udata.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    } else {
        JOptionPane.showMessageDialog(null, "Unable to delete");
    }
}

public boolean RemoveUserFromFile(int index) {
    File Mf = new File("AllUserRecords.txt");
    File Tf = new File("Uoutput.txt");
    try {
        BufferedReader Ubr = new BufferedReader(new FileReader(Mf));
        PrintWriter Upw = new PrintWriter(new FileWriter(Tf));
        String line;
        while ((line = Ubr.readLine()) != null) {
            if (line.trim().length() == 0) {
                continue;
            }
            if (!line.startsWith(String.valueOf(getValueAt(index, 0)))) {
                Upw.println(line);
            }
        }
        Upw.close();
        Ubr.close();
        Mf.delete();
        Tf.renameTo(Mf);
        return true;
    } catch (FileNotFoundException e1) {
        return false;
    } catch (IOException ioe) {
        return false;
    }
}

public void addRow(UserInformation userinf) {
    if (addUserToFile(userinf.toString())) {
        Udata.add(userinf);
        fireTableRowsInserted(Udata.size() - 1, Udata.size() - 1);
    }
}

public boolean addUserToFile(String useri) {
    try {
        File f = new File("AllUserRecords.txt");
        if (!f.exists()) {
            return false;
        } else {
            FileWriter fw = new FileWriter(f.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(useri);
            bw.close();
            return true;
        }
    } catch (Exception e) {
        return false;
    }
}

@Override
public String getColumnName(int colu) {
    return col[colu];
}

@Override
public int getRowCount() {
    return Udata.size();
}

@Override
public int getColumnCount() {
    return col.length;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    UserInformation uinfoS = Udata.get(rowIndex);
    Object value = null;
    switch (columnIndex) {
        case 0:
            value = uinfoS.getID();
            break;
        case 1:
            value = uinfoS.getFname();
            break;
        case 2:
            value = uinfoS.getLname();
            break;
        case 3:
            value = uinfoS.getGender();
            break;
        case 4:
            value = uinfoS.getDate();
            break;
        default:
            value = "...";
    }
    return value;
}
}

第二课:

public class UserPage extends JFrame implements ActionListener {

private AllUser userModel;
private JTable uTable;
JButton addUser;
JButton deleteUser;
JButton mainButton;
JButton exitButton;
JTextField tf1;
JButton searchButton;
JButton editButton;
JLabel resultLbl;
JMenuItem mainpageItem;
JMenuItem exitItem;
JMenuItem bookMenuItem;

public UserPage() {
    setTitle("All User Information");
    userModel = new AllUser();
    uTable = new JTable(userModel);
    createMenus(this);
    add(new JScrollPane(uTable), BorderLayout.CENTER);
    add(buttonPanels(), BorderLayout.PAGE_START);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(800, 600);
    this.setLocation(300, 60);
    this.setResizable(false);
}

public final JPanel buttonPanels() {
    JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    addUser = new JButton("Add New User");
    deleteUser = new JButton("delete User");
    mainButton = new JButton("Main Page");
    editButton=new JButton("Edit");
    tf1 = new JTextField("              ");
    searchButton = new JButton("Search");
    resultLbl = new JLabel();
    exitButton = new JButton("Exit");

    addUser.addActionListener(this);
    deleteUser.addActionListener(this);
    mainButton.addActionListener(this);
    searchButton.addActionListener(this);
    exitButton.addActionListener(this);
    editButton.addActionListener(this);

    buttonsPanel.add(exitButton);
    buttonsPanel.add(mainButton);
    buttonsPanel.add(editButton);
    buttonsPanel.add(addUser);
    buttonsPanel.add(deleteUser);
    buttonsPanel.add(tf1);
    buttonsPanel.add(searchButton);
    buttonsPanel.add(resultLbl);

    return buttonsPanel;
}

public final void createMenus(JFrame jframe) {
    JMenuBar menuBar = new JMenuBar();
    JMenu Fmenu = new JMenu("File");
    JMenu Bmenu = new JMenu("Book");
    mainpageItem = new JMenuItem("Main Page");
    exitItem = new JMenuItem("Exit");
    bookMenuItem = new JMenuItem("Book Page");

    mainpageItem.addActionListener(this);
    exitItem.addActionListener(this);
    bookMenuItem.addActionListener(this);

    Fmenu.add(mainpageItem);
    Fmenu.add(exitItem);
    Bmenu.add(bookMenuItem);

    menuBar.add(Fmenu);
    menuBar.add(Bmenu);
    jframe.setJMenuBar(menuBar);
}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource()== editButton){
        int selectedRow=uTable.getSelectedRow();
        if(selectedRow>0){
            editUser(selectedRow);

        }
        else{
            JOptionPane.showMessageDialog(null, "Select a user");
        }

    }
}

public boolean searchCondition(String userid) {
    if (userid.trim().isEmpty()) {
        resultLbl.setText("Please Enter User ID");
        return false;
    }
    return true;
}

public void SearchUser(String userEntered) {
    boolean find = false;
    File f = new File("AllUserRecords.txt");
    try {
        FileReader Bfr = new FileReader(f);
        BufferedReader Bbr = new BufferedReader(Bfr);
        String Us;
        while ((Us = Bbr.readLine()) != null) {
            String[] Ust = Us.split("     ");
            String uID = Ust[0];
            String Ufname = Ust[1];
            String Ulname = Ust[2];
            String UGender = Ust[3];
            String Udate = Ust[4];
            if (uID.equals(userEntered.trim())) {
                resultLbl.setText("User Found,"
                        + "    " + Ufname + "  " + Ulname + "  " + UGender + "  " + Udate);
                tf1.setText("              ");
                find = true;
            }
        }
    } catch (FileNotFoundException e) {
        resultLbl.setText("File Not Found");
    } catch (IOException ioe) {
        resultLbl.setText("IO Error");
    } finally {
        tf1.setText("              ");
        if (!find) {
            resultLbl.setText("User Not Found");
            tf1.setText("              ");
        }
    }
}

public static void main(String[] args) {
    new UserPage().setVisible(true);
}

public void editUser(int row){
    new NewUserFrame(UserPage.this).setVisible(true);      

}
}

1 个答案:

答案 0 :(得分:3)

  1. FileIO删除有关AbstractTableModel的所有代码,将其移至单独的类,void(clean_up logics),

  2. (您的AbstractTableModel缺失)需要覆盖AbstractTableModel.setValueAt()

  3. (您的AbstractTableModel缺失)需要覆盖AbstractTableModel.isCellEditable()

  4. 我可以使用DefaultTableModel来完成这项工作,而不是要求覆盖AbstractTableModel所需的大部分方法(可能是isCellEditablegetColumnClass),这些方法也可以从JTableDefaultTableModel方面访问

  5. JTable的(您的AbstractTableModel)只能访问AbstractTableModel

  6. 中覆盖的方法