如何在JOptionPane中显示多行?

时间:2013-10-13 06:53:52

标签: java swing joptionpane

如何在一个对话框中显示所有这些信息?每次运行文件时都会出现不同的对话框,我真的需要它们出现在一个包含所有信息的对话框中。

JOptionPane.showMessageDialog(null,"Your Name:"+a1,"Output",JOptionPane.INFORMATION_MESSAGE );
JOptionPane.showMessageDialog(null,"Your age:"+age,"Output",JOptionPane.INFORMATION_MESSAGE );
JOptionPane.showMessageDialog(null,"Your Birth year:"+a3,"Output",JOptionPane.INFORMATION_MESSAGE );
JOptionPane.showMessageDialog(null,"Your Height:"+H,"Output",JOptionPane.INFORMATION_MESSAGE );
JOptionPane.showMessageDialog(null,"Your Weight:"+W,"Output",JOptionPane.INFORMATION_MESSAGE );
JOptionPane.showMessageDialog(null,"Your BMI:"+BMI,"Output",JOptionPane.INFORMATION_MESSAGE );

4 个答案:

答案 0 :(得分:7)

您可以使用HTML代码:

JOptionPane.showMessageDialog(null, "<html><br>First line.<br>Second line.</html>");

或者您可以传递一组对象:

  

对象数组被解释为一系列消息(每个消息一个)   对象)排列在垂直堆栈中

docs中所述。

答案 1 :(得分:5)

只需创建一个具有适当布局的JPanel,因为您要放置要放置的组件,然后将此JPanel添加到JOptionPane以显示该消息。

一个帮助您理解逻辑的小例子:

import java.awt.*;
import javax.swing.*;

public class JOptionPaneExample {
    private String name;
    private int age;
    private int birthYear;

    public JOptionPaneExample() {
        name = "Myself";
        age = 19;
        birthYear = 1994;
    }

    private void displayGUI() {
        JOptionPane.showMessageDialog(
            null, getPanel(), "Output : ",
                JOptionPane.INFORMATION_MESSAGE);
    }

    private JPanel getPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
        JLabel nameLabel = getLabel("Your Name : " + name);
        JLabel ageLabel = getLabel("Your Age : " + age);
        JLabel yearLabel = getLabel("Your Birth Year : " + birthYear);
        panel.add(nameLabel);
        panel.add(ageLabel);
        panel.add(yearLabel);

        return panel;
    }

    private JLabel getLabel(String title) {
        return new JLabel(title);
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new JOptionPaneExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

输出:

optionpaneexample

答案 2 :(得分:4)

查看Javadoc for JOptionPane,特别是顶部的消息部分。如果传入一个Object数组,其元素将放在对话框中的垂直堆栈中。

JOptionPane.showMessageDialog(null,
                              new Object[]{"line 1","line 2","line 3","line 4"},
                              JOptionPane.INFORMATION_MESSAGE);

答案 3 :(得分:0)

只需输入此内容即可,而不是所有这些行:

JOptionPane.showMessageDialog(null,"Your Name: " + a1 +"\n Your age: " + age +"\n Your Birth year: "+ a3 +
    "\n Your Height: " + H +"\n Your Weight: "+ W +"\n Your BMI: "+ BMI);