如何将图像和字符串放在JOptionPane的按钮中

时间:2013-03-23 14:31:32

标签: java swing jbutton jlabel joptionpane

我正在尝试创建一个包含图像和文本的按钮的JOptionPane。 JLabel和JButton同时允许文本和图像,但使用JLabel可以防止显示实际按钮,而使用JButton会使按钮在单击时不执行任何操作。让我发现它的唯一方法就是单独使用String或ImageIcon,这显然不是我想要的。

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

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分: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();
            }
        });
    }

}