3

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

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

4 回答 4

7

您可以使用HTML标签:

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

或者你可以传递一个对象数组:

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

文档中所述。

于 2013-10-13T06:56:18.097 回答
5

只需创建一个JPanel具有适当布局的组件,就像您要放置要放置的组件一样,然后将其添加JPanelJOptionPane以显示消息。

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

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);
    }
}

输出 :

选项窗格示例

于 2013-10-13T08:14:02.760 回答
4

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

JOptionPane.showMessageDialog(null,
                              new Object[]{"line 1","line 2","line 3","line 4"},
                              JOptionPane.INFORMATION_MESSAGE);
于 2013-10-13T06:56:43.900 回答
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); 
于 2018-09-23T11:11:42.440 回答