2013-10-13 39 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