Ibrahim Rayis
Ibrahim Rayis

Reputation: 15

How can I print an array of object in a GUI JPanel?

I have array of object named "supermarkets" in every object there is String value called Name and method to return the value of the name called get-name().
I want to print all the elements in the array using a GUI JPanel. What can I use to print it?
This is what I want to print:

for (int i=0; i<supermarkets.length;i++){
       supermarkets[i].get-name();
}

Upvotes: 0

Views: 2026

Answers (2)

fill͡pant͡
fill͡pant͡

Reputation: 1165

You may use a JOptionPane and more specifically a messageDialog which can be acheived by JOptionPane.showMessageDialog(Params); where params depend on the method you choose. Read the docs for more.

Example #1

StringBuilder text = new StringBuilder();
for (int i=0; i<supermarkets.length;i++){
    text.append("\n"+supermarkets[i].get-name());
}

JOptionPane.showMessageDialog(null,"Available supermarkets:"+text.toString());

Example #2

Example #1 is alright if the ammount of supermarkets is limited, but if it exeeds a specific number, the window will become so big that it wont fit in the screen. To prevent that from happening, here is an example where 4 supermarkets are displayed per line seperated by comma's

int supermarketsPerLine = 4;//The ammount of supermarkets displayed per line

StringBuilder text = new StringBuilder();
for (int i=0; i<supermarkets.length;i++){
    text.append(supermarkets[i].get-name()+", ");
    if(i%supermarketsPerLine == 0 && i>0) text.append("\n");
}
text.delete(text.length()-2, text.length()-1);// to remove the last comma (,) from the end of the list.     
JOptionPane.showMessageDialog(null,"Available supermarkets:\n"+text.toString());

I hope that helps.

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83577

You have several options:

  1. Create as many JLabels as you need and set the text of each element in them.

  2. Use JList.

  3. Create a class which extends JPanel and override paintComponent(). Use Graphics.drawString().

Of these, I think #2 is probably the best.

Upvotes: 1

Related Questions