2012-12-20 145 views
3

我想知道如何添加圖像到MessageDialog框。我試了下面的代碼,圖像無處可查將圖像添加到JOptionPane

else if(button == B){ 
String text = "blahblahblahblahblah"; 
    JTextArea textArea = new JTextArea(text); 

textArea.setColumns(30); 
textArea.setLineWrap(true); 
textArea.setWrapStyleWord(true); 
textArea.setSize(textArea.getPreferredSize().width, 1); 
Font font = new Font("Verdana", Font.BOLD, 12); 
textArea.setFont(font); 
textArea.setForeground(Color.BLUE); 
JOptionPane.showMessageDialog(
null, textArea, "Border States", JOptionPane.PLAIN_MESSAGE); 

image2 = new ImageIcon(getClass().getResource("borderstates.jpg")); 
    label2 = new JLabel(image2); 
    add(label2); 
+0

什麼是MessageDialogBox? –

+0

從showMessageDialog方法 – user1911773

+0

感謝大家的幫助!我使用梅爾和MadProgrammer的建議來解決這個問題! – user1911773

回答

4

什麼是MessageDialogBox?如果你的意思是將一個圖像添加到JOptionPane中,有方法重載接受一個圖標,所以這是解決這個問題的一種方法。另一種方法是用您的圖像和其他組件創建JPanel或JLabel,然後在JOptionPane中顯示它。

+0

我在代碼中看到了一個JLabel,但是如何將它放入JOptionPane中。注意:我是新來的Java和一般編程 – user1911773

+0

+1,還有HTML格式用於顯示多個圖像並在運行時調整它們的大小。 –

5

從上JOptionPane的javadoc的:

public static void showMessageDialog(Component parentComponent, 
            Object message, 
            String title, 
            int messageType, 
            Icon icon) 
          throws HeadlessException 

只是讓你形象的Icon,並將其添加爲第五個參數。

JOptionPane.showMessageDialog(null, textArea, "Border States", 
    JOptionPane.PLAIN_MESSAGE, image2); 

別忘了你使用它(移動排隊)之前定義圖像2

16

JOptionPane是一種非常靈活的API。

你的第一個停靠港應該是Java API DocsJava Trails,具體How to use Dialogs

enter image description hereenter image description here

public class TestOptionPane04 { 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       ImageIcon icon = new ImageIcon(TestOptionPane04.class.getResource("/earth.png")); 
       JOptionPane.showMessageDialog(
         null, 
         "Hello world", 
         "Hello", JOptionPane.INFORMATION_MESSAGE, 
         icon); 
       JOptionPane.showMessageDialog(
         null, 
         new JLabel("Hello world", icon, JLabel.LEFT), 
         "Hello", JOptionPane.INFORMATION_MESSAGE); 

      } 
     }); 
    } 
} 
+2

好的地球儀。這是我見過的'Hello world'最好的GUI版本。 :) –