微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何打印 JOptionPane 中的所有数组元素?

如何解决如何打印 JOptionPane 中的所有数组元素?

我有一个数组,我想在 JOptionPane 上打印它以获得如下结果:

enter image description here

数组是书籍列表。我不知道怎么办

以下是数组的代码

String[] booksOfSubGenre = new String[bookInfo.size()];
        for (int i = 0; i < bookInfo.size(); i++) {
            int j = 0;
            if (bookInfo.get(i).getSubGenre().equals(selectedSubGenreInComboBox)) {
                subGenreCount++;
                System.out.println(subGenreCount);
                booksOfSubGenre[j] = bookInfo.get(i).getBookName();
            }
        }

解决方法

使用 HTML 格式化文本输出。

因此您的文本字符串可能如下所示:

String text = "<html>There are two books of Sub-Genre Fantasy:<br>The Lost Hero<br>Another Book>";
,

要以该格式显示,您可以使用 String.format() 创建字符串模板并传入数据。

String text = String.format("There are %o books of Sub-Genre Fantasy: %s",subGenreCount,bookInfo.get(i).getBookName());
JOptionPane.showMessageDialog(null,text,"Query Result",JOptionPane.INFORMATION_MESSAGE);

要显示多本书,您可以将书名附加在一起并显示为一个字符串。

    String appendedText = "";
    int subGenreCount = 0;
    String[] booksOfSubGenre = new String[bookInfo.size()];
    for (int i = 0; i < bookInfo.size(); i++) {
        int j = 0;
        if (bookInfo.get(i).getSubGenre().equals(selectedSubGenreInCombobox)) {
            subGenreCount++;
            System.out.println(subGenreCount);
            booksOfSubGenre[j] = bookInfo.get(i).getBookName();
            appendedText += bookInfo.get(i).getBookName() + "\n";
        }
    }
    String text = String.format("There are %o books of Sub-Genre Fantasy: %s",appendedText);
    JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
,

在类javax.swing.JOptionPane的所有showMessageDialog方法中,第二个参数,名为message的类型是Object,这意味着它可以是任何类,包括像javax.swing.JList这样的Swing组件。

考虑以下事项。

import java.awt.BorderLayout;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class OptsList {

    public static void main(String[] args) {
        String[] booksOfSubGenre = new String[]{"The Lost Hero","The Hobbit","A Game of Thrones"};
        int count = booksOfSubGenre.length;
        String subgenre = "Fantasy";
        JPanel panel = new JPanel(new BorderLayout(10,10));
        String text = String.format("There are %d books of Sub-Genre %s",count,subgenre);
        JLabel label = new JLabel(text);
        panel.add(label,BorderLayout.PAGE_START);
        JList<String> list = new JList<>(booksOfSubGenre);
        panel.add(list,BorderLayout.CENTER);
        JOptionPane.showMessageDialog(null,panel,JOptionPane.INFORMATION_MESSAGE);
    }
}

运行上面的代码产生以下结果:

running app

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。