Question

I use this method to add a new row to my jtable and file too.

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:

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.

Was it helpful?

Solution

Looks like what you get in the file is a result of method toString() invocation on an object of this class: myproject.Library.BookInformation.

So the quickest fix in your case would be to override toString() method for BookInformation to return what you need.

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.

Unlike in another answer you do NOT have to change code for AddToFile if you override toString(). 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:

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

Another even better way would be to modify AddToFile method to accept BookingInformation as a parameter.

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;
    } 
}

OTHER TIPS

In your BookInformation class add a toString method like this

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

and then call AddToFile() like this

AddToFile(bookinfo.toString())

from AddRow method.

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.

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.

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top