尝试将面板投射到JOptionPane

时间:2018-07-31 23:36:20

标签: jpanel joptionpane dice

我试图将面板投射到JOptionPane信息消息中,面板最终将包含多个图像,具体取决于两个骰子的掷骰。我试图使骰子的图像填充三卷后,之后我将包括有关骰子卷的统计信息。但是,在运行程序时,JOptionpane会弹出空白(即使用户dice1或dice2为1) 有人可以告诉我我做错了吗。

import java.util.Random;
import java.util.Scanner;
import java.text.DecimalFormat;
import java.awt.*;
import javax.swing.*;
public class Dice extends JFrame {

   public static void main(String[] args){
    UIManager.put("OptionPane.minimumSize", new Dimension(500,500));
        JPanel panel = new JPanel();
        DecimalFormat df = new DecimalFormat("#.#"); //how to display percentage of results
        Scanner sc = new Scanner(System.in);
        System.out.println("How many times would you like to roll the dice?");
        int rolls = sc.nextInt();
        int[] counts = new int[rolls]; //creates an array of user-specified length (rolls)
        sc.close();
        for (int i = 0; i <= 3 && i < counts.length; i++){
        Random rand = new Random();
        int dice1 = rand.nextInt(6)+1;
        int dice2 = rand.nextInt(6)+1;
        System.out.println((dice1) + " " + (dice2));
        counts[i] = dice1+dice2;
        if(dice1 == 1 || dice2 == 1){
        ImageIcon dice01img = new ImageIcon("/diceface01.gif");
        JLabel diceface01 = new JLabel(dice01img);
        panel.add(diceface01); 
        JOptionPane.showMessageDialog(null,panel,"Information",JOptionPane.INFORMATION_MESSAGE); 
        }
        else {
         System.out.println("Nothing yet"); }
        }
        for(int i = 3; i < counts.length; i++){ //populates said array with each roll of the dice
            counts[i] = diceRoll();
            if(i < 3){
            System.out.println(counts[i]);
            }

1 个答案:

答案 0 :(得分:0)

您不需要JPanel即可将图像添加到JOptionPane

您可以执行以下操作:

if(dice1 == 1 || dice2 == 1){
    //Just an example path here
    ImageIcon dice01img = new ImageIcon("C:\\Users\\Downloads\\ball.jpg");

    //Here you just have to pass your `ImageIcon` in the last parameter of your `JOptionPane` and it'll work as you wished.     
    JOptionPane.showMessageDialog(null, "HELLO", "Information", JOptionPane.INFORMATION_MESSAGE, dice01img);
}