我正在做的是將使用將使用此代碼的程序:如何在Java中製作隨機圖片?
JLabel MyImage = new JLabel(new ImageIcon("image1.png"));
但是,我想打一個隨機的畫面出現,表示圖像2,圖像3,圖像4。
- 沒有使用
List
- 使用任何方法或數組不使用
Collections.shuffle
- :我如何通過使這個。
我正在做的是將使用將使用此代碼的程序:如何在Java中製作隨機圖片?
JLabel MyImage = new JLabel(new ImageIcon("image1.png"));
但是,我想打一個隨機的畫面出現,表示圖像2,圖像3,圖像4。
List
Collections.shuffle
試試這個
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
JLabel MyImage = new JLabel(new ImageIcon("image"+randomNum+".png"));
凡max
和min
是您的圖像的數量。對於4張圖片,說 圖像1,圖像2,圖像3,圖像4 min=1
max=4
試試這個:
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));
你真的應該在每個地方交換「START」和「END」。 –
Store中的字符串數組:
String[] images = new String[]{"image1.png", "image2.png", "image3.png", "image4.png"};
得到一個隨機數,並使用它作爲索引:
int index = (int) (Math.random() * (images.length - 1));
JLabel MyImage = new JLabel(new ImageIcon(images[index]));
你可以得到從陣列中隨機字符串:
String[] images = new String[]{"image1.png","image2.png","image3.png"};
JLabel MyImage = new JLabel(new ImageIcon(
images[(int)Math.floor(Math.random()*images.length)]));
或者你可以得到imageX.png一個隨機數:
int imagecount = 5;
JLabel MyImage = new JLabel(new ImageIcon("image" + (int)(Math.floor(Math.random()*imagescount)) + ".png"));
感謝您的注意,您無法定義像 – grexter89
@ grexter89這樣的數組。固定。爲什麼不同的語言如此不同... – user2555349
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
}
** **爲什麼你不希望使用列表或'Collections.shuffle'?瞭解原因將有助於我們提供有用的激勵。 –