Presenting random pictures using JOptionPane icon and Math.random - java

I am taking a programming class, and I have to make an instrument "play". I want to use Math.random to create a random number between either 0-9 or 0-10 and have that number correspond to a picture in an array displayed via JOptionPane icon. My only issue is, how can I create a program that will correspond a random int to a picture and then present it using JOption Pane. Here is what I have so far:
public static String Flute(String pickYourInstrument, String instrument){
//try to assign variables to pictures in an array
ImageIcon icon = new ImageIcon("/home/james/programmingpics/A_Flute");
JOptionPane.showMessageDialog(null, "A Note", "A Note with Flute",
JOptionPane.OK_OPTION, icon);
for (int i = 0; i < 1000; i++) {
int random = 1 * (int) (Math.random() * 10);
System.out.println(random);
}
}
I am stuck, I stopped after I realized that I didn't know how to make the ImageIcon icon into an array (I have nine other pictures to make an icon for). Does anyone have an idea how I could create the program?

Simply create an array of ImageIcon, then the random number obtained can be used as an index to that array to get the corresponding icon. Something as simple as
int randomNumber = //.... get random int
ImageIcon myIcon = iconArray[randomNumber];

Related

Randomize colors in array on button click

I am trying to Randomize the colors automatically on a single button click. I am able to randomize and display the background color, but I have to click the button each time to get a different color. I am trying to click the button once and it automatically loop through the array and display the colors automatically. I know I need some form of loop around the array, but I have no clue where to put it.
private View windowView;
private Button clickMe;
private int[colors];
colors=new int[]{Color.CYAN, Color.GREEN, Color.RED};
for (int i = 0; i < colors.length; i++) {
Random random = new Random();
int randomNum = random.nextInt(colorArrayLength);
windowView.setBackgroundColor(colors[randomNum]);
}
I do not understand why this is not looping through the array. Any hints and assistance would be much appreciated.
I believe you are randomly selecting the color and setting it in the background. However as it is inside a loop, it is changing so fast that the change is not notable in the visual rendering. You need to pause few milliseconds to see the change visually.
You may try out out the following:
private View windowView;
private Button clickMe;
private int[colors];
colors=new int[]{Color.CYAN, Color.GREEN, Color.RED};
final int[] finalColors = colors;
final View finalWindowView = windowView;
for (int i = 0; i < finalColors.length; i++) {
Random random = new Random();
final int randomNum = random.nextInt(finalColors.length);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Do after 500ms
finalWindowView.setBackgroundColor(colors[randomNum]);
}
}, 500 * i);
}
Try out this it will helpful to you
private int getMatColor(String typeColor)
{
int returnColor = Color.BLACK;
int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getApplicationContext().getPackageName());
if (arrayId != 0)
{
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.BLACK);
colors.recycle();
}
return returnColor;
}
Your code isn't really randomizing an array, but simply picking a random color from your array.
There's a slight difference in this. Randomizing an array means the order of every item in your array becomes randomized. There is no way for repeats to be possible for this.
Whereas, randomly selecting a color from your array might make it possible for you to have the same color selected.
What you're doing is the latter and it's doing that task properly.
Therefore, your code isn't considered looping through an array. You're simply selecting a random color from the array for n number of times, with n being the size of your array.
Additionally, the colors you're randomly picking aren't displaying to windowView because the colors are being changed immediately.
For example, your for loop might turn windowView to CYAN, but immediately afterwards the loop will change it to RED. Thus, it'll only display the very last random value that is selected from your array and you won't see any of the previous color changes.
If you want to see the changes, you need to add a delay between each random color change.
What's colorArrayLength? no this variable. Codes like below are run normally.
for (int i = 0; i < colors.length; i++) {
Random random = new Random();
int randomNum = random.nextInt(colors.length);
button.setBackgroundColor(colors[randomNum]);
}
But even this, the view's background color is the last color after loop, you can not see the result of color looping effect. If you want to see the process of color changing, maybe add Timer.schedule() method.

How to find the ID Name of a JLabel Array in Java with MouseListener

What I have done.
I have created an array of JLabel like that:
static JLabel numbers[] = new JLabel[25];
I Have given to each of the numbers[each of this] a random number between 1 and 80.
I have added to each of numbers[] array a MouseListener.
I want to make something like, once I press a specific label to change itself background. But to do that I have to detect the ID of the JLabel has been pressed.
The Question:
How can I get the name or the number of the array on JLabel that has been pressed?
So far I only know how to get the text from it with the following code:
JLabel l = (JLabel) e.getSource();
int strNumber = Integer.parseInt(l.getText());
I want the ID of numbers[THIS], not the text but the number of array.
In Button listener, I know how to do that, but in MouseListener is not working...
(At least with the methods I tried to...(e.getSource().getName(); etc.)
You've got the array, you've got a reference to the pressed JLabel: e.getSource();, so simply iterate through the array to find the one that matches the other. e.g.,
#Override
public void mousePressed(MouseEvent e) {
Object source = e.getSource();
int index = -1;
for (int i = 0; i < numbers.length; numbers++) {
if (numbers[i] == source) {
index = i;
break;
}
}
}
// here index either == the array item of interest or -1 if no match
Side issue: that array should not be static, and that it is static suggests that you have some design issues with your program that need to be fixed.

How do I assign numbers a graphic to be shown in a JLabel

I am creating a higher or lower card game, and currently, it generates a random number from 1 to 13 as just a simple string label (1,2,3,4 etc), depending on what number gets pulled.
Instead of this, I would like to show a graphic of the card corresponding to the number.
public int getRandomNumber(){
Random r = new Random();
int nr = r.nextInt(13);
return nr;
}
...
JLabel label = new JLabel(getRandomNumber(), JLabel.CENTER);
To Update Label text you can use this method
public void updateLabel(int nr){
label.setText(nr+"");
//place this method inside your Jframe class extend from javax.swing.Jframe
}
If you want to put an image according to the number. Supose you have an array of 13 images(numbers)//Image images[13];
then you can use this
public void setIcon(int nr){
ImageIcon icon = new ImageIcon(images[nr]);
label.setIcon(icon);
}
I think that what you are looking for is adding an Icon to a JLabel.
You can do that using the setIcon method which accept any implementation of Icon, as for instance ImageIcon.
Something like the following should work:
ImageIcon imgIcon = new ImageIcon(URL_OF_THE_PIC));
jLabel.setIcon(imgIcon);
and whenever a new card gets picked you can change text and Icon accordingly.

Java GUI - Getting random value from array

So I have this 2d array of buttons and I have an array of images. I want to get the images on the buttons but I want the images to be on random buttons every time the program starts. Like this:What I want it to look like. Right now I can only get one color to be on all of the buttons by changing the value of icons when I make the new JButton. What I think I need to do is have Math.Random() set to a variable and to get a random value from the array of images and then put the variable in icons[] when i declare the new JButton but I don't know if this is right and don't know how to do it. I did some searching and tried using this:
var randomValue = icons[Math.floor(Math.random() * icons.length)];
but I get an error saying
possible loss of precision, required int, found double.
Help would be greatly appreciated. If you want me to post the entire code let me know.
// 2D Array of buttons
buttons = new JButton[8][8];
for(int row=0; row<8; row++)
{
for (int col=0; col<8; col++)
{
buttons[row][col] = new JButton(icons[0]);
buttons[row][col].setLocation(6+col*70, 6+row*70);
buttons[row][col].setSize(69,69);
getContentPane().add(buttons[row][col]);
}
}
// Array of images
public static ImageIcon[] icons = {new ImageIcon("RedButton.png"),
new ImageIcon("OrangeButton.png"),
new ImageIcon("YellowButton.png"),
new ImageIcon("GreenButton.png"),
new ImageIcon("BlueButton.png"),
new ImageIcon("LightGrayButton.png"),
new ImageIcon("DarkGrayButton.png")};
I'd simplify this greatly by putting all my ImageIcons in an ArrayList, calling java.util.Collections.shuffle(...) on the ArrayList, and then passing out the ImageIcons from the shuffled ArrayList in order. Or if your buttons allow for repeated icons, then use a java.util.Random variable, say called random and simply call random.nextInt(icons.length) to get a random index for my array.
As an aside, please for your own sake, don't use null layout and absolute positioning. Your grid of JButtons is begging to be held in a GridLayout-using JPanel. Begging.
As an aside, why are you posting questions on the same project but using different names? You've similar posts but different user names in both of your other posts here:
JButtons won't update on button click
My New Game JButton is not working?
Before you set the icons on the JButton use this shuffle function...
public ImageIcon[] shuffle(ImageIcon[] icons)
{
int index = 0;
ImageIcon temp = 0;
for(int i = icons.length -1; i > 0; i--)
{
index = r.nextInt(i + 1);
temp = icons[index];
icons[index] = icons[i];
icons[i] = temp;
}
return icons;
}

drawing random image libgdx

I am learning java game development with libgdx and have the following issue.
I have a Rectangle array which I iterate through and draw an image according to the position of the rectangle.
My Questions is how do I draw a random image every render but still keep drawing the same random image until it leaves the screen. currently it is drawing the same image but I would like know how to draw a different pipe image every iter.
Thank you
My Iterator
Iterator<Rectangle> upperIter = upperPipes.iterator();
while(upperIter.hasNext()) {
Rectangle upperpipe = upperIter.next();
upperpipe.x -= 8 * Gdx.graphics.getDeltaTime();
if(upperpipe.x < -32) upperIter.remove();
My draw method
public void drawPipes(){
batch.begin();
for(Rectangle upperPipe: Pipes.lowerPipes) {
batch.draw(Assets.pipeImg, upperPipe.x, upperPipe.y, upperPipe.width, upperPipe.height);
batch.end();
}
One great way to get repeatable random data is to use a Random object (java.util.Random is suitable for game usage), and provide it with a non-random seed. Each time you put in the seed and request the same sequence of number types+ranges, you will get the same (psuedo-)random numbers. When you want different numbers, just change the seed.
As an example:
Random rand = new Random(1234);
System.out.println(rand.nextInt()); // an int from Integer.MIN to Integer.MAX
System.out.println(rand.nextInt(100)); // an int from 0 to 100
Will always output the following, every single time.
-1517918040
33
But change the seed (in the constructor for Random), and the output values will change. rand.setSeed(seed) will reset the Random to start its sequence over.
You could use this to produce the same set of random numbers over and over while the rect is on screen.
However, a more direct and simple way would be to to just generate one random number for each rect when it is created, and store that number until it leaves:
public void drawPipes(){
for(int i = 0; i<Pipes.color.size; i++){
num = Pipes.color.get(i);
}
for(Rectangle bottomPipe: Pipes.lowerPipes) {
switch(num){
case 0:
batch.draw(Assets.redPipeImg, bottomPipe.x, bottomPipe.y, bottomPipe.width, bottomPipe.height);
break;
case 1:
batch.draw(Assets.yellowPipeImg, bottomPipe.x, bottomPipe.y, bottomPipe.width, bottomPipe.height);
break;
}
}
}
SOLVED!!
I created a custom pipe class and just created an array of pipes, each new pipe object that went into the array took a random image.
I iterated through the array, and called the draw method on each pipe object.
Simple and it works perfect

Categories