Reputation: 11
I have created a library Class of which has an ArrayList of Books called booklist.
public class Library {
//Fields
String libraryName;
ArrayList<Book> booklist;
//Constructor
public Library() {
this.libraryName = "Mt Baker";
}
public Library(String libraryName) {
this.libraryName = libraryName;
this.booklist = new ArrayList<Book>();
I have created a print method which works great to print the ArrayList to console.
public void printBooks() {
for (Book s : booklist)
System.out.println("Title: \t" + s.getTitle() + "\t\tAuthor: " + s.getAuthor() +
"\tYear: " + s.getYear() + "\tISBN :" + s.getISBN());
}
I cannot work out how to code the actionPerformed that would allow this method to print the ArrayList into the JTextArea. I have tried various iterations:-
String op = evt.getActionCommand();
Library x = new Library();
ArrayList <Book> y = new ArrayList<>();
if (op.equals("Show Library")) {
GUI.this.libraryResult.setText(y.printBooks().toString());
}
libraryResult is the JTextField, "Show Library" the JButton Listener Event.
Other advice on this site recommends use of append and toString, but I have not managed to make them work. Any advice much appreciated.
Upvotes: 0
Views: 112
Reputation: 964
GUI.this.yourButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = getAsString();
GUI.this.libraryResult.setText(text);
}
});
...
// Put this method somewhere else (where there is still access to your booklist)
public String getAsString() {
StringBuilder sb = new StringBuilder();
for (Book s : booklist) {
sb.append("Title: \t" + s.getTitle() + "\t\tAuthor: " + s.getAuthor() + "\tYear: " + s.getYear() + "\tISBN :" + s.getISBN());
}
return sb.toString();
}
Upvotes: 1