user3191018
user3191018

Reputation: 9

How to make search result all in one box? Insted of (JOptionPane seperate boxes)

Hello I have an ArrayList with 5 phones, 2 of them are from "Samsung manufacture" how would I display them all in one? Instead of separate boxes?

String conta1 = "Samsung";
for(int i=0;i<PhoneList.size();i++){
    if(conta1.equalsIgnoreCase(PhoneList.get(i).getMfg())){
        JOptionPane.showMessageDialog(null,PhoneList.get(i));
    }

Upvotes: 0

Views: 82

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208974

You can use a JLabels and add them to a JPanel, using whatever layout you find fit. Then add that JPanel to the JOptionPane. Something like

JPanel panel = new JPanel(new GridLayout(0, 1);
for(int i=0; i<PhoneList.size(); i++){
if(conta1.equalsIgnoreCase(PhoneList.get(i).getMfg())){
    panel.add(new JLabel(PhoneList.get(i)); // not sure what .get(i) returns
}                                           // but it must be a string passed to the label
JOptionPane.showMessageDialog(null, panel);

Note: As pointed out in comment, you need to pass a String to the JLabel. If there is a toString() in the object that PhoneList.get(i) returns, then call it (PhoneList.get(i).toString()). If each object's toString() method displays multiple lines, you can use HTML. You can google How to add multiple lines to a JLabel for some answers to that.


UPDATE

See full example here using HTML. Note, you can always use more than one JLabel also in the loop. You could add thee labels the panel, each iteration. For integers, just use String.valueOf(int) to pass to the label.

enter image description here

import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.MatteBorder;

public class TwoLineLabel {


    public static void main(String[] args) {
        List<Phone> phones = new ArrayList<>();
        phones.add(new Phone("Galaxy", 12345));
        phones.add(new Phone("iPhone", 12345));

        JPanel panel = new JPanel(new GridLayout(0, 1));
        for (Phone phone: phones) {
            String html = "<html><body style='width:100px'>Phone: " + phone.getName() 
                    + "<br/>Model: " + phone.getModel() + "</body></html>";
            JLabel label = new JLabel(html);
            label.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK));
            panel.add(label);

        }
        JOptionPane.showMessageDialog(null, panel, "Phone List", JOptionPane.PLAIN_MESSAGE);
    }

}

class Phone {
    private String name;
    private int model;

    public Phone(String name, int model) {
        this.name = name;
        this.model = model;
    }

    public String getName() {
        return name;
    }

    public int getModel() {
        return model;
    }
}

Upvotes: 2

Related Questions