2013-03-23 48 views
0

我試圖製作一個帶有圖像和文本按鈕的JOptionPane。 JLabel和JButton都允許同時使用文本和圖像,但是使用JLabel可以防止顯示實際的按鈕,而使用JButton可以讓按鈕一旦點擊就不會執行任何操作。使我找到的唯一方法是自己使用String或ImageIcon,這顯然不是我想要的。如何將圖像和字符串放在JOptionPane的按鈕中

JLabel[] members = { 
     new JLabel(one.name,one.image,JLabel.LEFT), 
     new JLabel(two.name,two.image,JLabel.LEFT), 
     new JLabel(three.name,three.image,JLabel.LEFT), 
     new JLabel(four.name,four.image,JLabel.LEFT), 
     new JLabel("Continue",new ImageIcon("mog.gif"),JLabel.LEFT)}; 
    JButton[] members = { 
     new JButton(one.name,one.image), 
     new JButton(two.name,two.image), 
     new JButton(three.name,three.image), 
     new JButton(four.name,four.image), 
     new JButton("Continue",new ImageIcon("mog.gif"))}; 
    String[] members = { 
     one.name, 
     two.name, 
     three.name, 
     four.name, 
     "Continue"}; 

     choice= JOptionPane.showOptionDialog(null, "Here are your party members", "Party Members", JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE, new ImageIcon("mog.gif"), members, members[4]); 

有沒有人知道如何解決這個問題?

+2

也許您希望創建並顯示包含組件的模態JDialog,而不是JOptionPane。 – 2013-03-23 14:35:48

回答

0

,使其工作,我發現的唯一方法是通過自身使用String或ImageIcon的

退房Compound IconText Icon。您可以使用圖標和文本(以圖標表示)創建自定義圖標:

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

public class OptionPaneButton 
{ 
    private static void createAndShowUI() 
    { 
     ImageIcon icon = new ImageIcon("About16.gif"); 
     JButton button = new JButton(); 
     TextIcon text = new TextIcon(button, "Maybe"); 
     CompoundIcon compound = 
      new CompoundIcon(CompoundIcon.Axis.X_AXIS, button.getIconTextGap(), icon, text); 

     Object options[] = {compound, "Not Now", "Go Away"}; 

     int value = JOptionPane.showOptionDialog(null, 
      "Would you like some green eggs to go with that ham?", 
      "A Silly Question", 
      JOptionPane.YES_NO_CANCEL_OPTION, 
      JOptionPane.QUESTION_MESSAGE, 
      null, 
      options, 
      options[2]); 

     System.out.println(value); 

     if (value == JOptionPane.YES_OPTION) 
     { 
      System.out.println("Maybe"); 
     } 
     else 
     { 
      System.out.println("Not today"); 
     } 
    } 

    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       createAndShowUI(); 
      } 
     }); 
    } 

} 
相關問題