你好,我有一个ArrayList
有5部手机,其中2部来自"三星制造"
我如何将它们全部展示在一起?而不是单独的盒子?
String conta1 = "Samsung";
for(int i=0;i<PhoneList.size();i++){
if(conta1.equalsIgnoreCase(PhoneList.get(i).getMfg())){
JOptionPane.showMessageDialog(null,PhoneList.get(i));
}
答案 0 :(得分:2)
您可以使用JLabels
并使用您认为合适的任何布局将其添加到JPanel
。然后将 JPanel
添加到JOptionPane
。像
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);
注意:正如评论中指出的那样,您需要将String
传递给JLabel
。如果toString()
返回的对象中有PhoneList.get(i)
,则将其调用(PhoneList.get(i).toString()
)。如果每个对象的toString()
方法显示多行,则可以使用HTML。您可以谷歌How to add multiple lines to a JLabel获取一些答案。
<强>更新强>
使用HTML查看此处的完整示例。请注意,您也可以在循环中始终使用多个JLabel
。您可以在每次迭代时为面板添加标签。对于整数,只需使用String.valueOf(int)
传递给标签。
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;
}
}