How to select random pictures in Java?

三世轮回 提交于 2020-07-18 08:28:23

问题


I'm making a program that will use a that will use this code:

JLabel MyImage = new JLabel(new ImageIcon("image1.png"));

But, I want to make a random picture appear, say image2,image3,image4. How do I make this by:

  • Not using a List
  • Not using Collections.shuffle
  • using any method or an array.

回答1:


Try this

Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
JLabel MyImage = new JLabel(new ImageIcon("image"+randomNum+".png"));

Where max and min are the the numbers of your images. For 4 images, say image1,image2,image3,image4 min=1 max=4




回答2:


Store the strings in an array:

String[] images = new String[]{"image1.png", "image2.png", "image3.png", "image4.png"};

Get a random number and use it as index:

int index = (int) (Math.random() * (images.length - 1));
JLabel MyImage = new JLabel(new ImageIcon(images[index]));



回答3:


You could get a random string from an array:

String[] images = new String[]{"image1.png","image2.png","image3.png"};
JLabel MyImage = new JLabel(new ImageIcon(
    images[(int)Math.floor(Math.random()*images.length)]));

Or you could get a random number for imageX.png:

int imagecount = 5;
JLabel MyImage = new JLabel(new ImageIcon("image" + (int)(Math.floor(Math.random()*imagescount)) + ".png"));



回答4:


Try this:

private static int START = 1;
private static int END = 4;

Random rand = new SecureRandom();
String imagePath = String.format( //
    "image%d.png", //
    rand.nextInt(Math.abs(START - END) + 1) + END //
);

JLabel MyImage = new JLabel(new ImageIcon(imagePath));



回答5:


package Pictures;

import javax.swing.JOptionPane;


/**
 *
 * @author denc18
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lblDisplay = new javax.swing.JLabel();
        btnShow = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        lblScore = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnShow.setFont(new java.awt.Font("Yu Gothic UI", 1, 18)); // NOI18N
        btnShow.setText("show");
        btnShow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowActionPerformed(evt);
            }
        });

        jLabel2.setText("impala elephant lion tiger cat dog");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(145, 145, 145)
                        .addComponent(btnShow))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(108, 108, 108)
                        .addComponent(lblDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(44, 44, 44)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(15, 15, 15)
                                .addComponent(lblScore, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(33, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(71, 71, 71))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(43, 43, 43)
                        .addComponent(lblScore, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(31, 31, 31)
                .addComponent(btnShow)
                .addContainerGap(34, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        
    int count = (int)(Math.random()*7);
    int score = 0;

    private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {                                        
    if (count == 1)
    {
        lblDisplay.setIcon( new javax.swing.ImageIcon("dog.PNG")); 
        String name = JOptionPane.showInputDialog("what is the Animal you see");

        if("dog".equalsIgnoreCase(name))
        {
           JOptionPane.showMessageDialog(null, name);
           score = score + 10;
           lblScore.setText("your score =" + score);
        }
        else
        {
            JOptionPane.showMessageDialog(null,"incorrect");
            score = score - 5;
           lblScore.setText("your score =" + score);
        }
    }
    if (count == 2)
    {
        lblDisplay.setIcon( new javax.swing.ImageIcon("cat.PNG"));
        String names = JOptionPane.showInputDialog("what is the Animal you see");

        if("cat".equalsIgnoreCase(names))
        {
           JOptionPane.showMessageDialog(null, names);
           score = score + 10;
           lblScore.setText("your score =" + score);
        }
        else
        {
            JOptionPane.showMessageDialog(null,"incorrect");
            score = score - 5;
           lblScore.setText("your score =" + score);
        }
    }
     if (count == 3)
    {
        lblDisplay.setIcon( new javax.swing.ImageIcon("lion.PNG"));
        String names = JOptionPane.showInputDialog("what is the Animal you see");

        if("lion".equalsIgnoreCase(names))
        {
           JOptionPane.showMessageDialog(null, names);
           score = score + 10;
           lblScore.setText("your score =" + score);
        }
        else
        {
            JOptionPane.showMessageDialog(null,"incorrect");
            score = score - 5;
           lblScore.setText("your score =" + score);
        }
    }
     if (count == 4)
    {
        lblDisplay.setIcon( new javax.swing.ImageIcon("tiger101.PNG")); 
        String name = JOptionPane.showInputDialog("what is the Animal you see");

        if("tiger".equalsIgnoreCase(name))
        {
           JOptionPane.showMessageDialog(null, name);
           score = score + 10;
           lblScore.setText("your score =" + score);
        }
        else
        {
            JOptionPane.showMessageDialog(null,"incorrect");
            score = score - 5;
           lblScore.setText("your score =" + score);
        }
    }
      if (count == 5)
    {
        lblDisplay.setIcon( new javax.swing.ImageIcon("elephant.PNG")); 
        String name = JOptionPane.showInputDialog("what is the Animal you see");

        if("elephant".equalsIgnoreCase(name))
        {
           JOptionPane.showMessageDialog(null, name);
           score = score + 10;
           lblScore.setText("your score =" + score);
        }
        else
        {
            JOptionPane.showMessageDialog(null,"incorrect");
            score = score - 5;
           lblScore.setText("your score =" + score);
        }
    }
        if (count == 6 )
    {
        lblDisplay.setIcon( new javax.swing.ImageIcon("impala.PNG")); 
        String name = JOptionPane.showInputDialog("what is the Animal you see");

        if("impala".equalsIgnoreCase(name))
        {
           JOptionPane.showMessageDialog(null, name);
           score = score + 10;
           lblScore.setText("your score =" + score );

        }
        else
        {
            JOptionPane.showMessageDialog(null,"incorrect");
            score = score - 5;
           lblScore.setText("your score =" + score);
        }
    }
    count = count + 1;
// TODO add your handling code here:
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnShow;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblDisplay;
    private javax.swing.JLabel lblScore;
    // End of variables declaration                   
}


来源:https://stackoverflow.com/questions/21478905/how-to-select-random-pictures-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!