Loading images into an array [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to load several images into an array. But for some reason, I get a NullPointerExeption when trying to do the actual loading (ImageIO.read()). I can't see whats wrong, probably from fiddeling around with it too much that I got blind for the mistake.
This is the loop that tries to load the images:
for (int i = 0; i <= 1; i++) {
try {
image[i] = ImageIO.read(new File(String.format("TDs/TD%d.png", i)));
bg[i] = ImageIO.read(new File(String.format("BGs/BG%d.png", i)));
} catch (IOException e) {
}
}
I currently have only two images to switch between, but I'll change that soon.
The painting happens using
g2d.drawImage(bg[1], 0, 0, null);
Both variables are initialized by
Image[] image, bg;
And last but not least proof that all images are actually there is found
Thanks for helping a stupid person.
EDIT: Thank you alot for the answers, as initiaizing the array this way works!
I feel like an idiot now since I looked at all other array inits to find that they were initialized exactly the same way as you told me... Sorry for stealing your time!
PS: No need to handle IOExeptions since these are textures for a game - they don't change and you can't / shouldn't change them either. I will add a Messagebox with a message in case someone decides to mess around anyways.

You need to create a new array. You only declare the array like so:
Image[] image;
But to store elements in your array you have to initialize it like so:
Image[] image = new Image[2] // value count
For your example you could try this
int imageCount = 2;
Image[] image = new Image[imageCount];
for (int i = 0; i < imageCount; i++) {
try {
image[i] = ImageIO.read(new File(String.format("TDs/TD%d.png", i)));
bg[i] = ImageIO.read(new File(String.format("BGs/BG%d.png", i)));
} catch (IOException e) {
}
}
Or as an alternative, if you don't know how many values you want to store. You could use an ArrayList. Like so:
ArrayList<Image> images = new ArrayList<>();
//add image
images.add(ImageIO.read(new File(String.format("TDs/TD%d.png", i))));

When you are initializing an array of images, you might want to try to do something like this:
Image[] image = new Image[2]; //or replace 2 by the amount of images you will be loading.
Image[] bg = new Image[2]; //same for this one.
This way the array is initialized properly.

Related

(Kind of solved but still appreciate better answers) Android Studio: How to identify certain special pages in a PDF file?

I am writing an app that generates Maths worksheets for school students. It will, for example, generate 2 to 5 pages of simple Maths questions and 1 to 2 pages of answers. The PDF can be saved to file and loaded again later. Then it has a print function that can print all the pages. I want to make it skip printing the answer pages.
Is it possible to automatically identify which pages are the answer pages? I can only think of a workaround by making those answer pages have special height or width but not even sure if this works. Are there any better ways to do this?
Ok, I continued the project and used the following method: when constructing the PDF, I put the word "Answer on the top left corner with a gray rectangle surrounding it drawn with drawRect(). Then before the actual printing, I used the following code inside the PrintDocumentAdapter() class to check whether the color of the pixel 0,0 is gray or not.
#Override
public void onStart() {
if (parcelFileDescriptor != null) {
try {
pdfRenderer = new PdfRenderer(parcelFileDescriptor);
} catch (IOException e) {
e.printStackTrace();
}
}
int tempTotal = pdfRenderer.getPageCount();
Bitmap[] tempBitmap = new Bitmap[tempTotal];
finalTotal = tempTotal;
for (int pageNum = 0; pageNum < tempTotal; pageNum++) {
PdfRenderer.Page tempPage = pdfRenderer.openPage(pageNum);
tempBitmap[pageNum] = Bitmap.createBitmap(WS_WIDTH, WS_HEIGHT, Bitmap.Config.ARGB_8888);
tempPage.render(tempBitmap[pageNum], null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
if (tempBitmap[pageNum].getPixel(0, 0) == Color.GRAY) {
finalTotal--;
}
tempPage.close();
}
}
It works fine. At least should cause no problem if the users only attempt to print PDF files constructed with my app. :P
Please tell me if you know a better way to do this. Thanks!

How to create sequence with thread.sleep in Java

I'm trying to create a simple sequence that basically consists on a JLabel's text being set to a value using an array and a for cycle. However it waits a certain time, before it changes.
My code looks something like this:
private String[] images = {"ball_00.bmp",
"ball_01.bmp",
"ball_02.bmp",
"ball_03.bmp",
"ball_04.bmp",
"ball_05.bmp",
"ball_06.bmp",
"ball_07.bmp",
"ball_08.bmp",
"ball_09.bmp",
"ball_10.bmp"};
public void runGif(){
for(int x = 0; x < this.images.length; x++) {
try {
System.out.println(images[x]);
this.lbl_image.setText(images[x]);
this.panel_CENTER.add(lbl_image);
this.lbl_image.setVisible(false);
this.lbl_image.setVisible(true);
System.out.println("I'm waiting");
Thread.sleep(CurrentSpeed);
System.out.println("I'm back");
}
catch(Exception e) {e.getStackTrace();}
System.out.println(x);
}
}
However I'm getting no output and the only thing I see on my JFrame is the label displaying "GIF", which is the default text that I set it to.
I don't know what migth be causing this issue, and would be very grateful if someone could help me.
Thank you for your attention in advance!

How do I change alpha of an image view multiple times using thread.sleep?

I am trying to create an animation for my game. I am trying to make an animation of a coin flip that will stop under certain conditions.
So far I have tried to change an image view multiple times within one method and using thread.sleep to delay the transition between the pictures.
Using 12 different images I am now trying to make it so the alpha of the first image will set to 0 and the second image will set to one, the the second image will set to 0 and the third will set to 1, etc...
The way I am currently trying to do it is by putting images inside of an array of ImageViews and then calling them sequentially.
setContentView(R.layout.coin_flip_screen);
for(int i = 0; i < 4; i++){
headsTails[i].animate().alpha(0).setDuration(100);
headsTails[i+1].animate().alpha(1).setDuration(100);
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
final int size = imageView.length;
final int animTime = 300;
final Handler animationHandler = new Handler();
Runnable animationRunnable = new Runnable() {
int i = 0;
#Override
public void run() {
if(i == size-1){
animationHandler.removeCallbacks(this);
return;
}
imageView[i++].animate().alpha(0f).setDuration(animTime).start();
imageView[i].animate().alpha(1f).setDuration(animTime).start();
animationHandler.postDelayed(this, animTime);
}
};
animationHandler.post(animationRunnable);
This code will iterate through all your imageviews in the array and stop itself once all the images are consumed.
Play along with your animTime variable until you get the perfect animation effect. Ideally it should be around 300 to 500 ms.
I will personally not use array of imageviews to create this effect as
it will eat up the memory. There are many more efficient ways to do
the coin flip animation, which you can google when you get time.
This should fix it
headsTails[i].animate().alpha(0).setDuration(100).start();

Android change background dynamically randomly from array

I am new to Android and I am trying to change the background of an ImageView in Java. This part is working. The problem is I have a 4 images and I would like to randomly choose one and display the image.
For example I have an array of drawables as such:
String[] images = new String[4];
images[0] = "R.drawable.i1";
images[1] = "R.drawable.i2";
images[2] = "R.drawable.i3";
images[3] = "R.drawable.i4";
I was trying to use this to choose a random one:
int idx = new Random().nextInt(images.length);
String random = (images[idx]);
However, I cannot seem to get the setBackground for the imageview to work with these.
For example, I tried:
images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );
I know I am not doing it correctly however that is what I would like to do.
You can try this:
int[] images = new int[4];
images[0] = R.drawable.i1;
images[1] = R.drawable.i2;
images[2] = R.drawable.i3;
images[3] = R.drawable.i4;
int idx = new Random().nextInt(images.length);
int random = (images[idx]);
images.setBackgroundDrawable( getResources().getDrawable(images[random]) );
Your problem seems to be, that you want to call a Method through a String. Thats absolutly nonesense unless you work with java SQL calls or XML...whatever. you need the actual image Object if you call your draw method.
well there is a simple solution :D
Instead of using an String[]. Use a ArrayList<Image>
after that you can call the method list.shuffle().
some pseudo Code:
ArrayList<Image> yourImages = new Arraylist<>();
yourImages[1] = image1
yourImages[2] = image2
...
yourImages.shuffle(); //shuffles your list
print(yourImages[1]);
print(yourImages[2]);
...
the first advatage is that your pictures will be displayed at random.
the second advantage is that there is no duplicate of each displayed picture.
PS: It would also work with an Image[] + the Random class. But how come, choose a String[]. a String is a representation of an Text... not an image.

Adding using Images GUI

I'm a beginner. I'm making a kid's math game. All it has to do is add the 2 pictures given. The problem is, I don't know how the JTextField will know that the answer is correct. Here's the picture.
ImageIcon[] images = new ImageIcon[10];
images[0] = new ImageIcon("0.jpg");
images[1] = new ImageIcon("1.jpg");
images[2] = new ImageIcon("2.jpg");
images[3] = new ImageIcon("3.jpg");
images[4] = new ImageIcon("4.jpg");
images[5] = new ImageIcon("5.jpg");
images[6] = new ImageIcon("6.jpg");
images[7] = new ImageIcon("7.jpg");
images[8] = new ImageIcon("8.jpg");
images[9] = new ImageIcon("9.jpg");
ImageIcon[] image = new ImageIcon[10];
image[0] = new ImageIcon("0.jpg");
image[1] = new ImageIcon("1.jpg");
image[2] = new ImageIcon("2.jpg");
image[3] = new ImageIcon("3.jpg");
image[4] = new ImageIcon("4.jpg");
image[5] = new ImageIcon("5.jpg");
image[6] = new ImageIcon("6.jpg");
image[7] = new ImageIcon("7.jpg");
image[8] = new ImageIcon("8.jpg");
image[9] = new ImageIcon("9.jpg");
int image_number = (int) (Math.random() * 10);
int image_number1 = (int) (Math.random() * 10);
Pic1.setIcon(images[image_number]);
Pic2.setIcon(image[image_number1]);
I'm not sure if I understood your question correctly, but you can store the value of a pic in some variable in Image.
It's been some time since I've coded in java, but I remember there are fields to store data.
After which all the JTextField has to do, is get the data associated with the 2 images currently being shown and see if the answer is correct or not.
Another good option, can be to name the images equal to their value i.e. an image named "7.png" is actually a diagram showing 7, that way all you have to do, is figure out what 2 images are being shown, parse their name and check for accuracy with the user input.
Update
Just did some quick research - http://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html
ImageIcon contains a field description, you can simply set that field when creating instances of it & retrieve the one currently rendered.
ImageIcon[] images = new ImageIcon[10];
images[0] = new ImageIcon("0.jpg");
images[0].setDescription("0");
//Other code
then somewhere at some other place, click of a button or keypress of JTextField, it can be retrieved like :
Integer x=Integer.parseInt(Pic1.getIcon().getDescription());
One thing you might consider doing is creating a wrapper class around the image, which not only maintains a reference to the image, but the value of the image
public class NumberImage {
private Image image;
private int value;
public NumberImage(int value, Image image) {
this.value = value;
this.image = image;
}
public int getValue() {
return value;
}
public Image getImage() {
return image;
}
}
This way, you can calculate the answer by simply adding the two values properties together within your program
The other thing you already have is the two indexes of the images to be displayed, wch is the same numerical value of the image to be displayed...
That is, based on your example, image_number == 7 and image_number1 == 5, therefore, you already have the information you need to calculate the answer ;)

Categories

Resources