1

I am currently working on a point-of-sale system that has a JList that displays everything the customer purchased. After ending the transaction, I want to display the contents of the entire list into a JTextArea. I use the following code:

String s = listModel.toString();
jTextArea.append(s);

The JTextArea displays an odd-looking set of codes rather than printing the contents of the list.

I have read other articles related to my problem, but all articles that I have read only provides answers for printing a single item from the list but not all. Thank you everyone!

Francis Rubio
  • 175
  • 4
  • 18
  • for example DefaultListModel has .toString() method defined as follows: `public String More ...toString() { return delegate.toString(); }` and the delegate is `Vector delegate = new Vector();` that means when called `listModel.toString()` in code you would get what `delegate.toString()` returns. Probably your listModel doesn't have a nice output printing toString method defined. Take a look at **overriding toString()** http://stackoverflow.com/a/10734148/1737819 – Developer Marius Žilėnas Mar 02 '16 at 05:24

2 Answers2

2

You may try this one,

int[] selectedIx = listbox.getSelectedIndices();  
String s = "";
for (int i = 0; i < selectedIx.length; i++) 
{
      s += " " + listbox.getModel().getElementAt(selectedIx[i]);
}
ta.setText(s);
Hetal Thaker
  • 717
  • 5
  • 12
0

Take the model and append each element to the JTextArea

for (int index = 0; index < listModel.getSize(); index++) {
    jTextArea.append(model.getElementAt(index).toString());
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I tried this code, but the jTextArea outputs prod2 45.75 javax.swing.JTextField[,989,84,90x......[plus a Very long string of text.] Is there any way to remove that? – Francis Rubio Mar 02 '16 at 05:01
  • Why are there text fields in your JList? – MadProgrammer Mar 02 '16 at 05:06
  • Here the thing, you should be putting components in you JList, the JList has renders for customising the data, you should just be putting the data into the JList – MadProgrammer Mar 02 '16 at 05:08
  • What I did is like this: When a customer purchases something, it is displayed in the jList. And when he ends the transaction, all of the products he purchased (w/c is in the jList) will appear in a jTextField (w/c serves as the receipt). But as I mentioned in the first comment, `prod2 45.75`(the product purchased, w/c is previously in the jList) appears, yes, but along with it comes this *odd-looking code* (`javax.swing.JTextField[,989,84,90x......`). Is there any way to remove that codes? – Francis Rubio Mar 02 '16 at 05:24
  • Don't add `JTextField`'s to the `ListModel` – MadProgrammer Mar 02 '16 at 05:30