2013-10-13 36 views
2

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

回答

5

您可以使用HTML标签:

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

或者您也可以通过对象的数组:

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

正如docs中所述。

3

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

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

只要建立适当布局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); 
    } 
} 

OUTPUT:

optionpaneexample