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 ;)
Related
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.
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.
I'm working on a homework project for an intro to java course. To practice calling methods and organizing tasks, we have to create two balloon objects s1 and s2 and modify their colors and altitudes using methods in a separate java class.
I have everything working fine, but not exactly to the requirements of the assignment. The sheet lists the method declarations and they cannot be changed, only the code within them can.
The method that is used to change a balloon's color is to be created as public void setColor(). This doesn't make sense to me, though. I'm using public void setColor(String color) for now.
How can I change the color property of a balloon object without passing anything to the setColor method?
I totally agree with #RealSkeptic but as your question says that changing the color without passing any value it means you need to generate the color each time your could use the following code. I'm not sure do this code is what you need.
public void setColor()
{
int red,green,blue;
red = green = blue = 0;
Random random = new Random();
int high = 255, low = 0;
red = random.nextInt(high-low)+low;
green = random.nextInt(high-low)+low;
blue = random.nextInt(high-low)+low;
color = new Color(red,green,blue);
//set this color to your balloon
}
Well, you can't specify any particular color without a parameter in the method. You can hardcode so that the color changes.
class Baloon {
private String[] colors = {"blue", "red" , "green"};
private int index = 0;
private String currentColor = colors[index];
public void setColor(){
index ++;
if (index = colors.length)
index = 0;
currentColor = colors[index];
}
}
I'm writing an application where I show markers on a map using the library Unfolding Maps.
The application lets the user choose a year and depending on that value other markers are shown. This works perfect, but when the user selects another year I can't seem to get the other markers shown.
I've tried to completely renew the map but after that first time it doesn't redraw a map.
Besides that I've tried to add a MarkerManager to the map but then I get errors of OpenGL.
setup function:
public void setup() {
/*
* Provincies, set zoom to 10
*/
size(1000, 800, OPENGL);
this.map = new UnfoldingMap(this, new Microsoft.RoadProvider());
map.zoomAndPanTo(belgie, 8);
map.setPanningRestriction(belgie, 1);
map.setZoomRange(8, 8);
drawOtherMarker();
//map.getMarkerManager(markerRemarck.get(keyM)).enableDrawing();
MapUtils.createDefaultEventDispatcher(this, map);
}
function that creates the MarkerManager and adds it to the map
private void createMarkers(ArrayList<double[]> dataMarker) {
float size = 0;
int i = 0;
ListIterator<double[]> dataIt = dataMarker.listIterator();
ArrayList<SimplePointMarker> markList = new ArrayList<SimplePointMarker>();
while (dataIt.hasNext()) {
double[] element = dataIt.next();
SimplePointMarker point = new SimplePointMarker(new Location(
element[0], element[1]));
if (element[2] > 1000)
size = 120;
else if (element[2] > 100)
size = 60;
else if (element[2] > 10)
size = 30;
else
size = 20;
point.setRadius(size);
point.setColor(color(64,64,64,100));
point.setStrokeColor(color(178,34,34));
point.setStrokeWeight(30);
point.setStrokeWeight(0);
point.setId(Integer.toString(i++));
markList.add(point);
}
MarkerManager man = new MarkerManager(markList);
map.addMarkerManager(man);
}
When the map is drawn and another set of markers must be drawn the following function is called:
public void drawOtherMarker(){
if(!markerRemarck.containsKey(keyM)){
markerRemarck.put(keyM, totalMark++);
createMarkers(dataMarkerProvince);
}
if(dataMarkerTown != null){
markerRemarck.put(keyM + "city", totalMark++);
createMarkers(dataMarkerTown);
}
for(int i = 0; i < totalMark;++i)
map.getMarkerManager(i).disableDrawing();
map.getMarkerManager(markerRemarck.get(keyM)).enableDrawing();
}
another function brings in the data required to make the markers. I just don't seem to manage to add a MarkerManager after the first draw.
EDIT
This map is placed inside a JPanel. And the years are choosen with the help of a JComboBox. Once a year is chosen the "dataMarker" variable containing the information for creating markers is updated
thanks in advance for helping me out.
I am very new to programming and I am totally lost on this homework assignment. The assignment is to have a gui that displays two different dice. When I click on the button the random number generator is supposed to have different images of the dice appear. I can get my images to appear when I don't have any "if" statements so I know that the path is working. When I add the "if" statements to assign the image for one of the dice I get an error that it cannot find symbol. Since this worked when the icon was statically assigned I assume it is the "if" statement causing the problem but it may come back to the random number. Please advise on what I am doing wrong. The code attached only has the non-working code for the left die.
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Random randomNumbers = new Random(); // Generates random numbers
int valLeft; // holds random number
int valRight; // holds random number
// get values for the dice
valLeft = randomNumbers.nextInt(6)+1; // range 1-6
valRight = randomNumbers.nextInt(6)+1; // range 1-6
// assign the image for the left die
if (valLeft==1)
{
ImageIcon leftDie = new ImageIcon("Die1.png");
}
if (valLeft==2)
{
ImageIcon leftDie = new ImageIcon("Die2.png");
}
if (valLeft==3)
{
ImageIcon leftDie = new ImageIcon("Die3.png");
}
if (valLeft==4)
{
ImageIcon leftDie = new ImageIcon("Die4.png");
}
if (valLeft==5)
{
ImageIcon leftDie = new ImageIcon("Die5.png");
}
if (valLeft==6)
{
ImageIcon leftDie = new ImageIcon("Die6.png");
}
// put image on label
imageLabelLeft.setIcon(leftDie);
// assign the image for the right die
ImageIcon rightDie = new ImageIcon("Die6.png");
imageLabelRight.setIcon(rightDie);
// remove the text from the labels
imageLabelLeft.setText(null);
imageLabelRight.setText(null);
// repack the frame for the new images
pack();
}
}
You are facing scope issues, leftDie scope is restricted to if block only so, move the ImageIcon leftDie == out of your if statements. Change this code:
if (valLeft==1)
{
ImageIcon leftDie = new ImageIcon("Die1.png");
}
To like this:
ImageIcon leftDie = null;
if (valLeft==1)
{
leftDie = new ImageIcon("Die1.png");
}
This should work.