Why do i get a NullPointerException when loading in ImageViews - java

I am currently making a poker game in java. The model works just fine. I do however also have to make a proper view for the game. I have to use javaFX scenebuilider as well as a graphic view class with actual code. In order to do this I made a superview to include both. When i am trying to run my application I get a white window and a nullpointerexception (for the code I included).
I do not get what I am doing wrong, since no one ever explained to me the basics of Imageviews and loading images in.
I made a package "res" where I embedded all the pics that represent my cards in the deck. Also note that k.toString() automatically generates the proper name of the file including the ".png" part. I printed it out and I am sure it works!
I use the for-loop to go through my list of cards that make the deck. My cards are generated in the Class Card. So basically I am going through an ArrayList of cards.
public void initializeDeck(){
for(Card c:model.getRound().getDeck().getList()){
int index = model.getRound().getDeck().getList().indexOf(c);
imv = new ImageView(new Image(getClass().getResourceAsStream("/res/"+k.toString()),95, 141, false, true));
deckView.add(index, imv);
}
getChildren().addAll(stapelView);
}

Related

ActionListener and dynamic(?) GUI

I've read through a dozen or so actionlistener/loop related questions here, but I'm not sure I've found my answer. I started on my first large Java project, a text RPG that's spiraled into around 5K lines of logic and game features which was functioning as intended using just the console - when I decided I'd try to build a Java swing GUI for it instead. Here's my problem:
I use a Room object which handles the description of where the player is at and also has an array of options for the player to choose next which it creates dynamically based on what cell the room's id is in on a csv file and what is beside it. I stopped outputting this to the console and instead started creating JButtons based on the options array like so:
public void showNarrate(){
add(dd,gridConstraints);
optionCopy.clear();
int i = 0;
for(JButton j : optionButtons){
//adding and formatting buttons to gridBagConstraint I also set actionCommand for each button to the triggerValue (ID of the next room which the button should take the player to)
}
//I tried using a copy of my JButton array here so I could have something to iterate over in actionListener after clearing out the original
//(Since it needs to be cleared so the next Room's buttons can be built after the player chooses an option)
for(JButton j : optionButtons){
optionCopy.add(j);
}
optionButtons.clear();
//dd is a seperate drawingComponent I used for outputting room descriptions which may be totally unnecessary at this point :/
dd.repaint();
setVisible(true);
}
Over in actionlistener (Same class) this is how I tried to swing it:
for(JButton j : optionCopy){
if(e.getActionCommand().equals(j.getActionCommand())){
Main.saveRoom = Main.currentRoom;
Main.currentRoom = j.getActionCommand();
System.out.println(Main.currentRoom);
}
}}
Then in my main class I call:
narrator.narrate(currentRoom, saveRoom); which takes care of some other logic concerning locked doors, encounters, etc.
Also in Main loop are some other methods related to autosave and tracking which rooms the player has visited. I know from other q/a i'v read on here that this is all pretty bad design, and I'm sttarting to understand that now, but my issue is this:
The first room of the game loads up fine, when I click a button it outputs to console(Just for testing) the correct trigger value of the room the button should be calling, so I'm getting that far, but how can I call the same method over again now?
-If I call narrate from actionListener it will wind up calling itself again and complain about ConcurrentModification.
-If I try to keep a loop going in my Main class it will keep looping and won't allow for the player to actually choose a button.
I've never used threads before, which I wonder might be the answer,and the closest thing to a related answer I've found is this:
Java: Method wait for ActionListener in another class
but I don't think moving actionListener to Main class would resolve my problem which is actionListener winding up calling itself recursively. And as for the observer-observable pattern... I just can't understand it :(
I appreciate any and all help, I've learned a LOT trying to make this thing work without seeking help as much as possible but this has stumped me.
Your loop in actionPerformed only checks whether a JButton exists in your optionList with the given actionCommand. However this can be done before actually doing something:
boolean contained = false;
for (JButton j : optionButtons)
if (j.getActionCommand().equals(e.getActionCommand()))
contained = true;
if (contained) {
// change room
}
now you can call narrate because you have finished iterating over the collection beforehand and will not get a ConcurrentModificationException

Placing one actor on top of another java

I am creating a program that is a recreation of the old game Frogger. A key part of the game is when the frog jumps across logs and to the other side of a river. However, when I make the frog move from the road to a log, the frog is positioned under the image of log instead of on top of the log. How can I make it so that the frog image lies above the log image?
I don't have an onDraw() method, at least I didn't write one. This is for an assignment in my class and we use a program called Greenfoot4Sofia. I created a subclass of Actor called Log, and I just used an option on the program to set the image of the actor to an image of a log, similarly with the frog.
Greenfoot is obviously not set up to make this sort of thing easy, but is intended for new programmers... curious.
So, I'm not familiar with Greenfoot, but looking over the API docs, I notice that World objects have a setPaintOrder(Class...) method. Perhaps you can use that? If you haven't already, I would make the log its own class that extends Actor, i.e.-
public class Log extends Actor {
// whatever code you have for your log
}
and do the same for your frogger.
Then (maybe) you can call the setPaintOrder() method of your World, i.e.-
myWorld.setPaintOrder( Log.class, Frogger.class );
This is obviously not the kind of code you can copy/paste, but hopefully it will get you on the right path. There will probably be other things you need to draw as well, so you can just create an array of Class to pass to setPaintOrder:
ArrayList<Class> paintOrderList = new ArrayList<Class>();
// add the things you need in the order you need them to paintOrderList
Class[] paintOrder = paintOrderList.toArray( new Class[ paintOrderList.size() ] );
myWorld.setPaintOrder( paintOrder );
I hope that helps.

App loses Images when built

For a project I am working on, I have made a Bingo Card. The basic functionality is that a Card is randomly generated and displayed in STD out as well as in a Swing GUI I made by hand. This application has multiple java files within.
BingoFinal.java - The main file. This is what's run when the program is run.
Bingo_Card.java - creates the Bingo card, prints it to STD out, and checks for bingo
BingoBG.java - Draws the background of the GUI with 2D graphics
DrawBingoCard.java - Calls BingoBG and also creates 25 labels with the board values. When Bingo_Card finds a matching number(inputted by STD IN), it no longer prints the number, and prints Chip.png(which is in the same package folder as the java files), a bingo chip image, making it look covered.
This works flawlessly when I run it through NetBeans, but when I clean and build it, then run the jar in terminal, everything works except for displaying the bingo chip image. Does anybody know why that would happen?
EDIT: Here is how I load the Image
ImageIcon chip; //declare ImageIcon
chip = new ImageIcon("chip75.png"); //define it as chip75.png. It is stored in package folder
JLabel B1Chip; //declare empty Label
B1Chip = new JLabel(chip); //define the Label with just the ImageIcon
B1Chip.setBounds(22, 112, chip.getIconWidth(), chip.getIconHeight()); //place at (22,112)
frame.add(B1Chip, null); //Add to frame
You should be accessing the images, by using :
ImageIcon chip = new ImageIcon(ClassName.class.getResource("/chip75.png"))
More information can be found on the info page of tag: embedded-resource A detailed answer regarding adding images to the NetBeans Project is mentioned on the info-page link.
More importantly, it would be wise, that you use ImageIO.read, since atleast it will let you know, if something goes wrong, by throwing IOException
Throws:
IllegalArgumentException - if input is null.
IOException - if an error occurs during reading.
ImageIcon on the other hand will hide the exception if any :-)
copy the image files into jar or give absolute path of the image files

Add a pictures to a card value?

I'm currently making a card game(made a custom one instead of lame poker), and basically I want to add pictures based on the value of the card. It's separated into a/b(a being the suit, b being the value).
Chunk of code I'm assuming will change to add pictures (or it's the card class?)
cards = new ArrayList < > ();
for (int a = 0 ; a <= 3 ; a++)
{
for (int b = 0 ; b <= 12 ; b++)
{
cards.add (new Card (a, b));
}
}
}
//Method to draw a card and remove card from the current deck
public Card PlayerCardDraw ()
{
Random generator = new Random ();
int index = generator.nextInt (cards.size ());
return cards.remove (index);
}
//Adds a card to player 1's hand kept in an arraylist to group cards to an individual player
public ArrayList <Card> p1Hand;
public ArrayList Card> P1CardDraw ()
{
p1Hand = new ArrayList < > ();
p1Hand.add (PlayerCardDraw ());
return p1Hand;
}
While I typed up the following answer, the asker wrote that he's using slick2D. That changes things.
New Answer
You should add slick2d as one of the tags for your question to get attention of the right crowd.
Old Answer
It seems like you have started with the underlying algorithm but you don't have any graphics or UI(User Interface) code done yet.
This means you need to decide What technology you will use to write your code.
If you want to write a game that sits on a computer (desktop/laptop) as an application and runs on it, then your options are Swing/AWT or Eclipse/SWT. They are pretty comparable, so I'd say whichever technology you can find an expert in.
Another option is that this is a game that will sit in a web server, and people will play it through web browser. In that case you need to look into javascript or Swing/AWT. Google has this technology called GWT which works over web and integrates java and javascript well-together. That might be a great option for your needs.
On the other hand, you might be writing a mobile game. If it's android then I'd suggest you look at it's sdk and make your decision. I believe you can write java apps for android. It might also be using GWT but not sure.
Or it could be an iPhone app. I don't think iPhone apps can be written in Java. You need to get iPhone's SDK and learn it.
Once you have decided on your platform and technology, that's when you are close to asking the question that you are asking right now.
Still before you ask this question, you need to figure out, what your main window will look like, what kind of buttons and other widgets will be there.
In short you are long way from putting that picture on the card, but with hard work and study of the technologies, you can get there.

Clearing a Double Array (I think I am doing it wrong)

Basically, I am building my own pokemon game, however whenever I go into a new "region" the tiles should reset and refresh, however, instead of clearing the old ones out, they just add onto the existing ones, thus causing a lot of issues.
I know that once I can successfully clear the old tiles, the game will refresh nice and neat for me.
I thought all i had to do was
buttonPanels = new JButton[row][col]
to make a new (clean) instance of the button array?
The whole board is a just a JButton array.
Two images below, one of before and one of after I go into a new region. You can see how how in the after photo all the new tiles just add onto the existing ones, which causes a lot of problems.
http://i421.photobucket.com/albums/pp296/rskom/before.png
http://i421.photobucket.com/albums/pp296/rskom/after.png
THANK YOU!! :)
First time at trying a rpg type thing, so don't be too critical of it so far.
Without seeing more of your code it is hard to answer your problem, but I think I know what the problem is. You show code where you do create a new array of JButton references. However, this does not destroy or remove the buttons you had in the previous array. If the buttons were visible somewhere (usually the case for having buttons) then they should first be removed from that container. This is probably the sequence you want if won want to replace all buttons.
For each button that is referenced from your array, remove it from the container where it is visible. Then you can replace your array, fill it with new buttons and finally add the buttons to the container where they should be visible again.
But then the real question is if you really do need to create a new array with new buttons. Can you not just reuse your existing one?

Categories