简体   繁体   English

将行添加到JTable和文件

[英]Add Row to JTable and File

I use this method to add a new row to my jtable and file too. 我使用此方法将新行添加到我的jtable和文件中。

But when i clicked to add button, That new record added to jtable, but when i see the text file, I found something like this: 但是,当我点击添加按钮时,该新记录添加到jtable,但是当我看到文本文件时,我发现了类似这样的内容:

myproject.Library.BookInformation@9899472 myproject.Library.BookInformation@9899472

where is my mistake? 我的错在哪里?

My code: 我的代码:

public class MainS extends JFrame{

   final AllBooks allBooks=new AllBooks();
   final JTable Btable=new JTable(allBooks);

   public MainS(){
       JButton AddBookButton=new JButton("Add New Book");
       AddBookButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) { 

           AddDialogS adddialog=new AddDialogS(MainS.this);
           adddialog.setVisible(true);
           BookInformation B_info=adddialog.getBookInfos();
           if(B_info != null){
               allBooks.AddRow(B_info);
           }
        }
    });

    JPanel Bpanel=new JPanel();
    Bpanel.setLayout(new FlowLayout());
    JScrollPane sp=new JScrollPane(Btable);
    Bpanel.add(sp);
    Bpanel.add(AddBookButton);
    this.add(Bpanel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setBounds(300, 60, 550, 550);
    this.setVisible(true);
   }

   public static void main(String[] args){
       new MainS();
   }
}

second class for add new record: 第二类添加新记录:

public class AddDialogS extends JDialog{
BookInformation bookinform=new BookInformation();

public AddDialogS(JFrame owner){
    super(owner,"Add New Book!", true);
    JButton OkButton=new JButton("Ok");
   final JTextField nameTF=new JTextField(10);
   JLabel namelbl=new JLabel("bookname");
   final JTextField dateTF=new JTextField(10);
   JLabel datelbl=new JLabel("bookDate");
   final JTextField idTF=new JTextField(10);
   JLabel IDlbl=new JLabel("bookId");


    OkButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            bookinform.setBookName(nameTF.getText().trim());
            bookinform.setBookDate(String.valueOf(dateTF.getText().trim()));
            bookinform.setBookID(String.valueOf(idTF.getText().trim()));
            AddDialogS.this.dispose();
        }
    });

    JPanel panel=new JPanel(new FlowLayout());
    panel.add(OkButton);
    panel.add(nameTF);
    panel.add(dateTF);
    panel.add(idTF);
    panel.add(namelbl);
    panel.add(datelbl);
    panel.add(IDlbl);
    this.add(panel);
    this.setBounds(10, 30, 400, 500);
}

public BookInformation getBookInfos(){
    return bookinform;
}
}

My table model Class: 我的桌子类:

public class AllBooks extends AbstractTableModel{
BookInformation Binfos1=new BookInformation();

String[] Bcol=new String[]{"Name","Date","Id"};
List<BookInformation> Bdata=new ArrayList<BookInformation>();

public AllBooks(){
    try{
        FileReader fr=new FileReader("AllBookRecords.txt");
        BufferedReader br=new BufferedReader(fr);
        String line;

        while( (line=br.readLine()) !=null){
            Bdata.add(initializeBookInfos(line));
        }
        br.close();
    }
    catch(IOException ioe){

    }
}

public static BookInformation initializeBookInfos(String str){
    BookInformation Binit=new BookInformation();
    String[] bookCellArray=str.split("     ");
    Binit.setBookName(bookCellArray[0]);
    Binit.setBookDate(bookCellArray[1]);
    Binit.setBookID(bookCellArray[2]);
    return Binit;
}

public void AddRow(BookInformation bookinfo){
    if(AddToFile(bookinfo)){
        Bdata.add(bookinfo);
        fireTableRowsInserted(Bdata.size()-1, Bdata.size()-1);
    }
    else{
        JOptionPane.showMessageDialog(null, "Unable Add To File"+bookinfo.getBookName());
    }
}

public boolean AddToFile(String bookinfos){
    try{       
        PrintWriter Bpw=new PrintWriter(new FileOutputStream("AllBookRecords.txt",true));
        Bpw.println(bookinfos);
        return true;
    }
    catch(IOException ioe){
        return false;
    } 
}

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

@Override
public int getRowCount() {
    if(Bdata !=null){
    return Bdata.size();
    }
    else{
        return 0;
    }
}

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

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    BookInformation binfo=Bdata.get(rowIndex);
    Object value;

    switch(columnIndex){

        case 0:
            value=binfo.getBookName();
            break;
        case 1:
            value=binfo.getBookDate();
            break;
        case 2:
            value=binfo.getBookID();
            break;
        default :
            value="...";  
    }
    return value;

}
}

My BookInformation Class: 我的书籍信息类:

public class BookInformation {

private String BookName;
private String BookDate;
private String BookID;

public String getBookName() {
    return BookName;
}

public void setBookName(String book_name) {
    this.BookName = book_name;
}

public String getBookDate() {
    return BookDate;
}


public void setBookDate(String book_date) {
    this.BookDate = book_date;
}


public String getBookID() {
    return BookID;
}

public void setBookID(String Book_id) {
    this.BookID = Book_id;
}
}

Thanks for help. 感谢帮助。

Looks like what you get in the file is a result of method toString() invocation on an object of this class: myproject.Library.BookInformation. 看起来你在文件中得到的是对该类对象的方法toString()调用的结果:myproject.Library.BookInformation。

So the quickest fix in your case would be to override toString() method for BookInformation to return what you need. 因此,在您的情况下最快的修复方法是覆盖BookInformation的toString()方法以返回您需要的内容。

public String toString() {
    return getBookName(); // Or whatever you see fit.
}

Even if later you'll change your code not to rely on toString() a meaningful implementation is not going to hurt. 即使稍后您将更改代码而不依赖于toString(),有意义的实现也不会受到伤害。

Unlike in another answer you do NOT have to change code for AddToFile if you override toString(). 与另一个答案不同,如果覆盖toString(),则不必更改AddToFile的代码。 However, if you don't modify code for BookingInformation, then you would have to craft string value when you call AddToFile similar to what was suggested: 但是,如果您不修改BookingInformation的代码,那么当您调用类似于建议的AddToFile时,您将不得不制作字符串值:

AddToFile(bookinfo.getBookName()) // Or whatever you see fit.

Another even better way would be to modify AddToFile method to accept BookingInformation as a parameter. 另一种更好的方法是修改AddToFile方法以接受BookingInformation作为参数。

public boolean AddToFile(BookingInformation bookinfos){
    try{       
    PrintWriter Bpw=new PrintWriter(new FileOutputStream("AllBookRecords.txt",true));
    Bpw.println(bookinfos.getBookName()); // Or whatever you see fit.
    return true;
    }
    catch(IOException ioe){
    return false;
    } 
}

In your BookInformation class add a toString method like this BookInformation类中添加这样的toString方法

public String toString(){
    return BookID + "     " + BookDate + "     " + BookName; 
}

and then call AddToFile() like this 然后像这样调用AddToFile()

AddToFile(bookinfo.toString())

from AddRow method. 来自AddRow方法。

There are any number solutions you could try. 您可以尝试任何数量的解决方案。

You could modify your AddToFile method to write to format the properties of the object as you need it. 您可以修改AddToFile方法以编写以根据需要格式化对象的属性。

This ensures that the format that the model writes the file in is what the model expects when it reads it back it. 这可以确保模型写入文件的格式是模型在读取文件时所期望的格式。

public boolean AddToFile(BookInformation bookinfos){
    try{       
        PrintWriter Bpw=new PrintWriter(new FileOutputStream("AllBookRecords.txt",true));
        StringBuilder sb = new StringBuilder(64);
        sb.append(bookinfos.getBookID()).append(";");
        sb.append(bookinfos.getBookName()).append(";");
        sb.append(bookinfos.getBookID()).append(";");
        Bpw.println(sb.toString());
        return true;
    }
    catch(IOException ioe){
        return false;
   } 
}

You can of course define your own format and delimiters. 您当然可以定义自己的格式和分隔符。 This has the benefit of allowing the model to control it's own format and does not effect any other part of the program, like using toString() would. 这样做的好处是允许模型控制它自己的格式,并且不会影响程序的任何其他部分,比如使用toString()

Alternativly, you could write a read/write method in the BookInformation class, passing in the PrintWriter and allowing the BookInformation to determine the format that the data should be maintained in. 或者,您可以在BookInformation类中编写读/写方法,传入PrintWriter并允许BookInformation确定应保留数据的格式。

This has the benefit of allowing other parts of the program to save the object in a uniform manner and if the format ever changes (ie you add new fields), it changes in one location 这样做的好处是允许程序的其他部分以统一的方式保存对象,如果格式发生变化(即添加新字段),它会在一个位置发生变化

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

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