Java label set icon with getComponent - java

I have a frame, in this frame I have 10 labels.
If I click on label then it icon should be set to "zoldgomb.jpg", if I click a second time it should be set to "sargagomb.jpg".
This part is working, now my question is: How can it be written so that I don't have to write this part down ten times for each of the 10 labels (label name A1-A11)?
if (event.getSource()==A1) {
if (x==1) {
A1.setIcon(new ImageIcon("zoldgomb.jpg"));
x=2;
}else if (x==2) {
A1.setIcon(new ImageIcon("sargagomb.jpg"));
x=1;
} }

event.getSource() return reference to your JLabel, you can use something like next:
if (event.getSource() instanceof JLabel) {
if (x == 1) {
((JLabel)event.getSource()).setIcon(new ImageIcon("zoldgomb.jpg"));
x = 2;
} else if (x == 2) {
((JLabel)event.getSource()).setIcon(new ImageIcon("sargagomb.jpg"));
x = 1;
}
}

Related

JPanel doesn't get new values (anymore)

So, I'm trying to program a Game of Life simulation (Conway), and I want to show it in a JFrame.
For this purpose, I've created a JPanel, and it works perfectly, until I try to actually show a new generation. With prints, I've figured out, that the list is actually correct inside the newGeneration() method, but when paint(Graphics g) gets called (aka, when I try to repaint the JFrame), the list isn't updating.
I'm sure I've missed something obvious, and I'm not well versed in Java, but it's just getting so annoying. I'd really appreciate your help.
Here's my code;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Main {
public static void main(String[] args) {
new GameOfLife();
}
}
class GameOfLife {
// Initialising all class wide variables; sorted by type
JFrame frame = new JFrame("Game of Life");
JPanel panel;
Scanner gameSize = new Scanner(System.in);
String dimensions;
String splitHorizontal;
String splitVertical;
String confirmation;
Boolean accepted = false;
Integer split;
Integer horizontal;
Integer vertical;
Integer livingNeighbours;
int[][] cells;
int[][] newCells;
public GameOfLife() {
// Prompt for game Size
System.out.println("Please enter your game size in the following format; 'Horizontal,Vertical'");
// Run until viable game Size has been chosen
while (!accepted) {
dimensions = gameSize.nextLine();
// Check for correct format
if (dimensions.contains(",")) {
split = dimensions.indexOf(",");
splitHorizontal = dimensions.substring(0, split);
splitVertical = dimensions.substring(split + 1);
// Check for validity of inputs
if (splitHorizontal.matches("[0-9]+") && splitVertical.matches("[0-9]+")) {
horizontal = Integer.parseInt(dimensions.substring(0, split));
vertical = Integer.parseInt(dimensions.substring(split + 1));
// Check for game Size
if (horizontal > 1000 || vertical > 1000) {
System.out.println("A game of this Size may take too long to load.");
} else {
// Confirmation Prompt
System.out.println("Your game will contain " + horizontal + " columns, and " + vertical + " rows, please confirm (Y/N)");
confirmation = gameSize.nextLine();
// Check for confirmation, anything invalid is ignored
if (confirmation.matches("Y")) {
accepted = true;
System.out.println("Thank you for your confirmation. Please select live cells. Once your happy with your game, press Spacebar to start the Simulation.");
// Setting parameters depending on Size
frame.setSize(horizontal * 25 + 17, vertical * 25 + 40);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
}
// Prompt asking for new dimensions in case of invalid dimensions or non confirmation
if (!accepted) {
System.out.println("Please enter different dimensions.");
}
}
// Creating list of cells
cells = new int[horizontal][vertical];
// Showing the empty panel for selection of live cells
panel = new PaintCells(horizontal, vertical, cells);
frame.add(panel);
// Select live cells
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (cells[(int) Math.ceil(e.getX() / 25)][(int) Math.ceil(e.getY() / 25)] == 1) {
cells[(int) Math.ceil(e.getX() / 25)][(int) Math.ceil(e.getY() / 25)] = 0;
} else {
cells[(int) Math.ceil(e.getX() / 25)][(int) Math.ceil(e.getY() / 25)] = 1;
}
frame.repaint();
}
});
// Simulation start
frame.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == ' ') {
newGeneration();
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
}
// Generating new generations
void newGeneration() {
newCells = new int[horizontal][vertical];
// Pause inbetween generations
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
* Way of Life Rules:
* Living cells with 2 or 3 living neighbours live on to the next generation.
* Dead cells with exactly 3 living neighbours become living cells in the next generation.
* Every other living cell dies.
*/
// iterate through every cell
for (int l = 0; l < vertical; l++) {
for (int k = 0; k < horizontal; k++) {
livingNeighbours = 0;
// check amount of neighbours
if (k - 1 > -1) {
if (l - 1 > -1) {
if (cells[k - 1][l - 1] == 1) {
livingNeighbours++;
}
}
if (l + 1 < vertical) {
if (cells[k - 1][l + 1] == 1) {
livingNeighbours++;
}
}
if (cells[k - 1][l] == 1) {
livingNeighbours++;
}
}
if (k + 1 < horizontal) {
if (l - 1 >= 0) {
if (cells[k + 1][l - 1] == 1) {
livingNeighbours++;
}
}
if (l + 1 < vertical) {
if (cells[k + 1][l + 1] == 1) {
livingNeighbours++;
}
}
if (cells[k + 1][l] == 1) {
livingNeighbours++;
}
}
if (l - 1 >= 0) {
if (cells[k][l - 1] == 1) {
livingNeighbours++;
}
}
if (l + 1 < vertical) {
if (cells[k][l + 1] == 1) {
livingNeighbours++;
}
}
// change cell value depending on amount of neighbours
if (cells[k][l] == 1) {
if (livingNeighbours < 2 || livingNeighbours > 3) {
newCells[k][l] = 0;
} else {
newCells[k][l] = 1;
}
} else {
if (livingNeighbours == 3) {
newCells[k][l] = 1;
}
}
}
}
cells = newCells;
frame.validate();
frame.paint(frame.getGraphics());
newGeneration();
}
}
// Our canvas
class PaintCells extends JPanel {
private Integer horizontal;
private Integer vertical;
private int[][] newOriginalCells;
// Get our X and Y from the original prompts
public PaintCells(Integer originalHorizontal, Integer originalVertical, int[][] originalCells) {
this.horizontal = originalHorizontal;
this.vertical = originalVertical;
this.newOriginalCells = originalCells;
}
#Override
public void paint(Graphics g) {
for (int i = 0; i < vertical; i++) {
for (int j = 0; j < horizontal; j++) {
// Check cell value
if (newOriginalCells[j][i] == 1) {
g.setColor(Color.black);
} else {
g.setColor(Color.white);
}
// paint according to value
g.fillRect(j * 25, i * 25, 25, 25);
if (newOriginalCells[j][i] == 1) {
g.setColor(Color.white);
} else {
g.setColor(Color.black);
} // maybe change style?
g.drawRect(j * 25, i * 25, 25, 25);
}
}
}
}
I'm guessing, the problem is somewhere in newGeneration(), but other than that, I really have no idea anymore.
You have a common problem which I had myself a few months ago.
Java Swing GUI system works in thread called Event Dispatch Thread (EDT). This thread handle events like mouse clicks, typing etc. and paint the components to the screen. You should use this thread not as your main thread, but as sub-thread which working only once a certain time/when event happens, and not let him run continuously. In your code, since the user choose the cell to live, this thread run non-stop (because you started the program inside a listener, which is part of the EDT), and your GUI stuck, because it's updating only at the end of the thread.
You can solve this by using javax.swing.Timer. Timer is an object that allows you do tasks once a while, and it is perfect to this problem.
Use code like this:
ActionListener actionListaner = new ActionListener(){
public void actionPerformed(ActionEvent e){
//Put here you ne genration repeating code
}
};
int delay = 1000;//You delay between generations in millis
Timer timer = new timer(delay, actionListener);
The code in the actionPerformed method will repeat every second (or any other time you want it to repeat), and every operation of the timer will recall EDT instead of let it run non-stop.

Java: Listen For Second KeyPress

I have a list of colors with numbers associated with them. I'd like to make it so that, if the user types in "2", it selects "2: Green"; if they type in "21", it selects "21: Yellow"; etc. I'm trying to use KeyPressed, and I think I need some way for the program to listen for the first number pressed and then wait a second to see if another is pressed. For example, something like this:
// The integer pressed will always be zero or positive.
private void jComboBox1KeyPressed(KeyEvent evt) {
int code = -1;
for(int i = 0; i < 10; i++) {
if (evt.getKeyCode() == i) {
if (code == -1) {
code = i;
} else {
code += i;
}
break;
}
}
// PSEUDO-CODE: if (KeyEvent newEvt is pressed within 1 sec) {
jComboBox1KeyPressed(newEvt);
}
}
Then, I suppose I'd have a key-value map with an index and the color numbers, and I'd set the selected item for jComboBox1 based on code (the selected color number).
I've got it working for a single keyPressed:
private void jComboBox1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_0) {
jComboBox1.setSelectedItem("2: Green");
}
else if (evt.getKeyCode() == KeyEvent.VK_1) {
jComboBox1.setSelectedItem("21: Yellow");
}
else if (evt.getKeyCode() == KeyEvent.VK_2) {
jComboBox1.setSelectedItem("13: Blue");
}
else if (evt.getKeyCode() == KeyEvent.VK_3) {
jComboBox1.setSelectedItem("2041: Red");
}
}
Here's the interface:
PLEASE NOTE: This is an example I quickly made and not the actual app I'm creating. My app involves many more number options, but as with this example, the numbers will always be positive.

How to render sprite array efficiently in j2me game?

I am working on a landscape java game.
I have a sprite array like this;
Sprite stickArray[] = new Sprite[10];
and initializing it like this with visibility as false.
for (int j = 0; j < stickArray.length; j++) {
if (stickArray[j] != null) {
stickArray[j].setPosition(stickX, stickY);
stickArray[j].setVisible(false);
}
}
Later I want to position it like one after another vertically on repeating a key.pressBool is false initially.
public void keyRepeatInGame(int keyCode) {
int gameKey = getGameAction(keyCode);
Graphics g = getGraphics();
if (gameKey == FIRE || keyCode == KEY_NUM5) {
pressBool = true;
}
}
Later I have written code like this;
Initially one Sticksprite is there.above this sprite, I want to place each sticks on clalling keyrepeat()in space key.
for (int i = 0; i < stickArray.length; i++) {
if (pressBool) {
if (i == 0) {
stickArray[i].setPosition(stickSprite.getX(),
stickSprite.getY() - stickSprite.getHeight());
stickArray[i].setVisible(true);
} else {
stickArray[i].setPosition(stickArray[i-1].getX(),
stickArray[i-1].getY() - stickArray[i].getHeight());
stickArray[i].setVisible(true);
}
}
}
This code is working partially.Stick is getting added on the sprite,all at once.
How can I change the code to make the sticks repeatedly getting added on calling keyrepeat() only, and make it visible one by one properly?
I changed the code with an additional condition and break statement like this;
if (pressBool) {
if (stickSprite != null && !stickArray[i].isVisible()
&& stickArray[i] != null) {
if (i == 0) {
stickArray[i].setPosition(
stickSprite.getX(),
stickSprite.getY());
stickArray[i].setVisible(true);
break;
} else if (i > 0) {
stickArray[i].setPosition(
stickArray[i].getX(),
stickArray[i - 1].getY()
- stickArray[i].getHeight());
stickArray[i].setVisible(true);
break;
}
}
}
It worked.

NumberFormatException and other problems while making a calculator in java

So I'm making a Java Calculator and walking into some errors upon clicking the function buttons (it compiles perfectly fine though).
The error on the 1st line in my CMD was a NumberFormat Exception. After some searching I figured out that somewhere in my code I was trying to get a double out of an empty string (basically what I'm trying to do is parse a double from the label text). I'm guessing it's this part:
// if statement that puts the labels text into the first or second number
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
Basically the problems are when i push the / * + or - button i get a NumberFormatExeption: For input string "/" etc.
I can't quite figure out how i have to fix this error (I'm still (somewhat) a beginner in Java).
Further down the line of errors (there were quite alot) were a whole lot of errors I didn't understand such as EventDispatchThread, EventQueue and many others. I couldn't find an explanation on my level of experience either so I'm asking for help here.
The numeric buttons all work fine.
At run: [http://gyazo.com/71cb4dde449ccf7ece44017388a71a0f]
Putting in numbers: [http://gyazo.com/5c7ab6c54ac6da180845c66866d66f8f]
All other buttons give errors in my CMD.
Here's my code (the spacing might be messed up in some parts):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
// import for Nimbus look
import javax.swing.UIManager.*;
public class Calculator extends JFrame implements ActionListener
{
private JPanel bottom = new JPanel(); private JPanel top = new JPanel();
private JLabel label = new JLabel(" ");
private JButton[] buttons = new JButton[16];
// booleans for calculator functions
boolean add = false, substract = false, devide = false, multiply = false, firstNumber = true;
// numbers that will be calculated
double number1, number2;
public Calculator()
{
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
// bottom panel
bottom.setPreferredSize(new Dimension(100,100));
bottom.setLayout(new BorderLayout());
//add bottom panel to frame
add(bottom);
// top panel
top.setPreferredSize(new Dimension(300,400));
top.setLayout(new GridLayout(4,4,3,3));
top.setBackground(Color.BLACK);
//dont add top panel to frame: you want top to be on bottom
// add top panel to bottom panel
bottom.add(top);
// label
label.setFont(new Font("Courier", Font.PLAIN, 20));
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(SwingConstants.RIGHT); // text is right-aligned
label.setOpaque(true);
// add the label to the bottom panel
bottom.add(label, BorderLayout.NORTH);
// creating buttons
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton("789/456*123+c0=-".substring(i, i+1));
buttons[i].addActionListener(this);
// add them to the top panel
top.add(buttons[i]);
}
// Nimbus look
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
//set to default somehow o.o
}
// frame setters
setTitle("Calculator");
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void Clear()
{
label.setText(" ");
}
#Override
public void actionPerformed(ActionEvent e)
{
//if's for all function buttons
if(e.getSource() == buttons[3])
{
// devide
devide = true;
substract = false;
add = false;
multiply = false;
firstNumber = false;
Clear();
label.setText("/");
}
if(e.getSource() == buttons[7])
{
// multiply
multiply = true;
substract = false;
devide = false;
add = false;
firstNumber = false;
Clear();
label.setText("*");
}
if(e.getSource() == buttons[11])
{
// add
add = true;
substract = false;
devide = false;
multiply = false;
firstNumber = false;
Clear();
label.setText("+");
}
if(e.getSource() == buttons[12])
{
// clear
label.setText("0");
number1 = 0.00;
number2 = 0.00;
add = false;
substract = false;
devide = false;
multiply = false;
firstNumber = true;
Clear();
}
if(e.getSource() == buttons[15])
{
// substract
substract = true;
add = false;
devide = false;
multiply = false;
firstNumber = false;
Clear();
label.setText("-");
}
// for loops that add the numbers on the buttons to the label
for(int i = 0; i < 3; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
for(int i = 4; i < 7; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
for(int i = 8; i < 11; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
for(int i = 13; i < 14; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}
// if statement that puts the labels text into the first or second number
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
// calculation
if(e.getSource() == buttons[14])
{
// calculate
if(devide){number1 = ((double)(number1) / (double)(number2)); }
if(multiply){number1 = ((double)(number1) * (double)(number2)); }
if(add){number1 = ((double)(number1) + (double)(number2)); }
if(substract){number1 = ((double)(number1) - (double)(number2)); }
label.setText(Double.toString(number1));
}
}
public static void main(String[] args)
{
new Calculator();
}
}
Lastly, the calculations made by the calculator are incorrect. I also can't wrap my head around what's causing that. Please bear in mind that I'm a beginner at Java and this is my first question on stackoverflow. Thanks in advance for helping me, whoever will :)
UPDATE: i fixed the errors by putting my code as follows:
if(e.getSource() == buttons[15])
{
// substract
substract = true;
add = false;
devide = false;
multiply = false;
firstNumber = false;
isNumberKey = false;
if(isNumberKey)
{
if(firstNumber)
{
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
number1 = Double.parseDouble(label.getText().trim());
} else {
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
number2 = Double.parseDouble(label.getText().trim());
}
}
Clear();
label.setText("-");
}
All i need to do now is fix the calculations...
Thanks for the help everyone!
Cannot delve totaly into your logic there, but here's some hints:
First, you don't have to guess where the error is. In case of uncaught exception like here, thread that produced it will print it's stack trace to console. It looks like this:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at mypackage.Calculator.actionPerformed(Calculator.java:229)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6297)
From here you see that exception happened in thread named AWT-EventQueue-0, which is swing's standard event dispatching thread (all GUI applications handles events in single thread). Another thing you search in stack trace is to find what line in your code thrown it. Here it's the line:
at mypackage.Calculator.actionPerformed(Calculator.java:229)
In source, it is line:
number2 = Double.parseDouble(label.getText().trim());
, so you guessed right. What you can do is add another boolean there which will be set only if number button is hit, and then change that part of code to something like:
if( isNumber){
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
}
Apart from that, instead of using multiple boolean flags for operation, use Java enum type
enum Operation {devide, substract, add, multiply};
your code will be more readable and "java" styled.
Good starting point, just go ahead!
Disclaimer: I'm on my phone so it's hard to parse your code; with that being said, I believe your number format exception deals with what is stored in the label text.
From the looks of it if you hit an operator button (like multiply), the labelText will be "*", then if you hit number button (like 5), the labelText will be "*5". Finally, if you hit the enter button now to go calculate the answer, Double.parseDouble(label.getText().trim()), will be ran which will throw the NumberFormatException. Using the operation flags, it looks like you don't even need to store the operator (unless you're trying to display the operator to the user); in that case you need to strip the operator from the string before trying the parse the double.
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
As for the other exceptions, in eclipse you can set a breakpoint to halt the program when a specific exception occurs. This will help you debug your code further.
more info on that here

Java Swing Dice Rolling Animation

I'm coding up a GUI game of craps. There is a JButton called "roll" which when clicked rolls the dice for the game. The GUI then displays what you rolled using jpeg's of die faces.
Everything works great, except I'm supposed to now add an animation to the GUI. My idea was to somehow rapidly display different face values for a short period of time (simulating a "roll") using the same method of displaying the jpeg's. However, as I'm sure you all know, that doesn't work.
I'm familiar with the idea of EDT and the Timer class, but I'm not sure exactly how to use them. Basically I want this animation to happen when I hit the "roll" button, and when the animation is finished, I want it to display what was actually rolled like it did before.
Any help would be greatly appreciated. Here's the code I have thus far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/* This is the GUI declaration */
public class NCrapsGUI extends JFrame {
//code...
/* Action when "roll" is clicked */
private void rollActionPerformed(java.awt.event.ActionEvent evt){
game.rollDice();
//Rolls both die
sumOfDice.setText(Integer.toString(game.getSum()));
//Displays the sum of the die
numRolls.setText(Integer.toString(game.getNumRolls()));
//Displays the number of rolls in each game
// <editor-fold defaultstate="collapsed" desc="Die JPEG's">
// If statements display the die face based on the number rolled
if (game.getDie1Value() == 1) {
die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face1.jpg")));
}
if (game.getDie1Value() == 2) {
die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face2.jpg")));
}
if (game.getDie1Value() == 3) {
die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face3.jpg")));
}
if (game.getDie1Value() == 4) {
die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face4.jpg")));
}
if (game.getDie1Value() == 5) {
die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face5.jpg")));
}
if (game.getDie1Value() == 6) {
die1Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face6.jpg")));
}
if (game.getDie2Value() == 1) {
die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face1.jpg")));
}
if (game.getDie2Value() == 2) {
die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face2.jpg")));
}
if (game.getDie2Value() == 3) {
die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face3.jpg")));
}
if (game.getDie2Value() == 4) {
die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face4.jpg")));
}
if (game.getDie2Value() == 5) {
die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face5.jpg")));
}
if (game.getDie2Value() == 6) {
die2Disp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/face6.jpg")));
}
//</editor-fold>
/*
* If the game is beyond the first roll, it checks to see if the sum of the
* values rolled equal 7 or the point value for a loss or win respectively.
* If it is a win, it adds a win. Likewise for a loss.
*/
if (game.getGameStatus() == 2) {
if (game.getSum() == game.getPoint()) {
game.addWin();
numWins.setText(Integer.toString(game.getWins()));
game.setGameStatus(1);
game.setPoint(0);
game.resetRolls();
return;
}
if (game.getSum() == 7) {
game.addLoss();
numLosses.setText(Integer.toString(game.getLosses()));
game.setGameStatus(1);
game.setPoint(0);
game.resetRolls();
return;
}
}
/*
* This checks to see if the game is on the first roll. If it is, it checks
* if the sum of the die is 7 or 11 for a win, or 2, 3, or 12 for a loss. If
* not, it passes it on to the next roll and sets the point value to the sum
*/
if (game.getGameStatus() == 1) {
game.setPoint(game.getSum());
dieSum.setText(Integer.toString(game.getPoint()));
if (((game.getSum() == 7) || ((game.getSum() == 11)))) {
game.addWin();
numWins.setText(Integer.toString(game.getWins()));
game.setPoint(0);
dieSum.setText(Integer.toString(game.getPoint()));
game.resetRolls();
return;
}
if (((game.getSum() == 2) || ((game.getSum()) == 3)) || (game.getSum()) == 12) {
game.addLoss();
numLosses.setText(Integer.toString(game.getLosses()));
game.setPoint(0);
dieSum.setText(Integer.toString(game.getPoint()));
game.resetRolls();
return;
} else {
game.setGameStatus(2);
}
}
}
EDIT WITH UPDATED CODE!!!
Here's where the Timer and array are declared:
public class NCrapsGUI extends JFrame
{
private Timer timer;
private int numPlayers;
private int totalIcons = 6;
private ImageIcon imageArray[];`
/* CODE */
And here is where the array is populated inside the NCrapsGUI constructor:
imageArray = new ImageIcon[totalIcons];
for (int i = 0; i < 6 ;i++)
{
int temp = i + 1;
imageArray[i] = new ImageIcon("face" + temp + ".jpg");
}
initComponents();`
This is the entire rollActionPerformed method. I'm guessing the Timer gets started right
at the beginning, but whenever I try to start it I get loads of error. However, when I
I made a new JPanel seperately, and made it implement action listener, I got no
errors. I tried adding implements ActionListner to this declaration, but NetBeans literally
would not let me type anything in.
private void rollActionPerformed(java.awt.event.ActionEvent evt) {
game.rollDice();
//Rolls both die
sumOfDice.setText(Integer.toString(game.getSum()));
//Displays the sum of the die
numRolls.setText(Integer.toString(game.getNumRolls()));
//Displays the number of rolls in each game
// <editor-fold defaultstate="collapsed" desc="Die JPEG's">
// If statements display the die face based on the number rolled
if (game.getDie1Value() == 1)
{
die1Disp.setIcon(imageArray[0]);
}
if (game.getDie1Value() == 2)
{
die1Disp.setIcon(imageArray[1]);
}
if (game.getDie1Value() == 3)
{
die1Disp.setIcon(imageArray[2]);
}
if (game.getDie1Value() == 4) {
die1Disp.setIcon(imageArray[3]);
}
if (game.getDie1Value() == 5) {
die1Disp.setIcon(imageArray[4]);
}
if (game.getDie1Value() == 6)
{
die1Disp.setIcon(imageArray[5]);
}
if (game.getDie2Value() == 1)
{
die2Disp.setIcon(imageArray[0]);
}
if (game.getDie2Value() == 2)
{
die2Disp.setIcon(imageArray[1]);
}
if (game.getDie2Value() == 3)
{
die2Disp.setIcon(imageArray[2]);
}
if (game.getDie2Value() == 4)
{
die2Disp.setIcon(imageArray[3]);
}
if (game.getDie2Value() == 5)
{
die2Disp.setIcon(imageArray[4]);
}
if (game.getDie2Value() == 6)
{
die2Disp.setIcon(imageArray[5]);
}
//</editor-fold>
/*
* If the game is beyond the first roll, it checks to see if the sum of the
* values rolled equal 7 or the point value for a loss or win respectively.
* If it is a win, it adds a win. Likewise for a loss.
*/
if (game.getGameStatus() == 2) {
if (game.getSum() == game.getPoint()) {
game.addWin();
numWins.setText(Integer.toString(game.getWins()));
game.setGameStatus(1);
game.setPoint(0);
game.resetRolls();
return;
}
if (game.getSum() == 7) {
game.addLoss();
numLosses.setText(Integer.toString(game.getLosses()));
game.setGameStatus(1);
game.setPoint(0);
game.resetRolls();
return;
}
}
`
Your basic idea behind the animation is a good one I think, but whether it works or not is all in the implementation details of course. I suggest
That you read in your images and make ImageIcons once, probably at the start of the program.
That you put the icons into an ImageIcon array with a length of 7 -- but you'll put an icon into the 1-6 slots, leaving the 0th item null.
That you use a Swing Timer to swap these icons randomly with some appropriate delay, say 200 or 300 msec.
That you use a a Random object to get a random number between 1 and 6, and then with this number as your array index, get the Icon out of the array.
That you display the ImageIcons in a JLabel (or two JLabels if you're displaying 2 die) and swap Icons by simply calling the JLabel's setIcon(...) method.
Edit
You state in your comment that you tried:
timer = new Timer(100,this);
And that's your problem -- your use of this. You shouldn't try to use the same ActionListner for everything. Instead create an ActionListener right there, where you need it. Something like,
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent actionEvt) {
// ... put your ActionListener's code here
}
});

Categories