Open Side Menu Go to the Top

02-05-2010 , 12:35 PM
Hey CTH!

I actually have no idea if I can even post this here... But I need 2+2's help. I tried posting my question on a programming forum, & not a single person has replied in a week or so. Other forums are ghey, I now realize that. It's not even a very technical question, I don't think!

Basically, the quick version of my problem is that my button clicks on a JButton are being consumed. & I have no idea why. I'm trying to write a game of craps with a very basic GUI. My idea is to create the screen by creating arrays of Icons, & just swap between the icons when things happen in my program. I'm not even sure if this is the right way to create a 'screen', but this is my first ever program (besides the hello worlds etc) & I'm teaching myself...

this is what my GUI looks like...


But when u click the buttons, nothing happens. As you can see in my code, I was testing the buttons by getting it to just swap out ImageIcons[]... But it's not doing anything

Ok, here's my code:

Spoiler:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;


public class CrapsGame extends JFrame implements ActionListener {


// initializing variables used in game

Random random = new Random(); // it's a dice game, after all...

// --- BUTTONS ---

private JButton newGameBtn, // creates new game
placeBetBtn, // places player bet amount
instructBtn, // instructions obv
rollDiceBtn; // rolls the virtual dice

// --- PANELS ---

private JPanel headPnl, // title/instruction panel
mainScrnPnl, // the 'screen' panel
bottomPnl; // button panel

// --- STRINGS ---

private String betNumber; // used to capture player bet as a string then parse to int

private String txtBankroll = "CURRENT BANKROLL: $";
private String txtPoint = "CURRENT POINT: ";
private String txtBet = "CURRENT BET AMOUNT: $";

// --- ICONS --- These represent the individual graphics on the screen

private Icon spacerPic = new ImageIcon(getClass().getResource("spacer.png"));
private Icon headPic = new ImageIcon(getClass().getResource("header.png"));
private Icon roll = new ImageIcon(getClass().getResource("diceBtnPic.png") );

private Icon rolledIcons[] = { // the added array index no# comment
// is so I can reference diff pics quickly while coding

new ImageIcon(getClass().getResource("rolled2.png")), // --[0]
new ImageIcon(getClass().getResource("rolled3.png")), // --[1]
new ImageIcon(getClass().getResource("rolled4.png")), // --[2]
new ImageIcon(getClass().getResource("rolled5.png")), // --[3]
new ImageIcon(getClass().getResource("rolled6.png")), // --[4]
new ImageIcon(getClass().getResource("rolled7.png")), // --[5]
new ImageIcon(getClass().getResource("rolled8.png")), // --[6]
new ImageIcon(getClass().getResource("rolled9.png")), // --[7]
new ImageIcon(getClass().getResource("rolled10.png")), //--[8]
new ImageIcon(getClass().getResource("rolled11.png")), //--[9]
new ImageIcon(getClass().getResource("rolled12.png"))} ;//--[10]


private Icon diceIcons[] = { // the pics that represent the 'screen'

new ImageIcon(getClass().getResource("1.png")), // --[0]
new ImageIcon(getClass().getResource("2.png")), // --[1]
new ImageIcon(getClass().getResource("2.png")), // --[2]
new ImageIcon(getClass().getResource("4.png")), // --[3]
new ImageIcon(getClass().getResource("5.png")), // --[4]
new ImageIcon(getClass().getResource("6.png"))}; //--[5]

private Icon wonLostIcons[] = {

new ImageIcon(getClass().getResource("rollAgain.png")) ,// --[0]
new ImageIcon(getClass().getResource("youWin.png")), // --[1]
new ImageIcon(getClass().getResource("youLose.png"))}; // --[2]

// --- BOOLEANS ---

boolean isGame; // is a game being played?
boolean isBroke; // does player have > 0?
boolean isBet; // has player placed bet amount?

// --- INTEGERS ---

int initialMoney = 1000; // player starting money
int currentMoney; // current player money
int betAmt; // player bet size
int betAmt1; // used to parse player input of bet amt (String) to int
int roll1; // calculates a dice roll (dice 1)
int roll2; // calculates a dice roll (dice 2)
int point; // used as the 'point' to roll against
int answer; // used to match rolls against the point

// --- LABELS ---

private JLabel header; // holds TITLE graphic
private JLabel scrn1; // LEFT side of the dice screen
private JLabel scrn2; // RIGHT side of the dice screen
private JLabel scrnBottom; // bottom 'in game graphic' panel eg. 'you rolled 4'
private JLabel winLose; // 2nd ingame graphic, 'roll again' or 'you win' etc

// --- JTEXTAREA

private JTextArea playerStatusBar; // player info panel


public CrapsGame() { // beginning frame constructor

super("Craps Game");


// ------------------------------ CREATING & ADDING EVERYTHING TO THE GUI -----



// creating labels & adding Icons

JLabel spacer = new JLabel(spacerPic);
JLabel header = new JLabel(headPic);
JLabel scrn1 = new JLabel(diceIcons[1]);
JLabel scrn2 = new JLabel(diceIcons[1]);
JLabel scrnBottom = new JLabel(rolledIcons[2]);
JLabel winLose = new JLabel(wonLostIcons[0]);


// creating buttons, adding actionListeners

JButton newGameBtn = new JButton("new game");
newGameBtn.addActionListener(this);
JButton placeBetBtn = new JButton("place bet");
placeBetBtn.addActionListener(this);
JButton instructBtn = new JButton("instructions");
instructBtn.addActionListener(this);
JButton rollDiceBtn = new JButton(roll);
rollDiceBtn.addActionListener(this);


// creating JTextArea for player 'info' bar

JTextArea playerStatusBar = new JTextArea(
" "
+txtBankroll +currentMoney
+"\n\n "
+txtPoint +point
+"\n\n "
+txtBet +betAmt, 5, 20);

playerStatusBar.setBackground(new Color(40,50,50));
playerStatusBar.setForeground(Color.WHITE);
playerStatusBar.setEditable(false);

// creating panels

JPanel headPnl = new JPanel();
JPanel mainScrnPnl = new JPanel();
JPanel bottomPnl = new JPanel();
JPanel topScrnPnl = new JPanel();

// setting backgrounds/colors & adding everything to the 3 main panels

headPnl.setBackground(new Color(40,50,50));
headPnl.add(header);
headPnl.add(instructBtn);

mainScrnPnl.setBackground(Color.BLACK);
mainScrnPnl.add(spacer);
mainScrnPnl.add(scrn1);
mainScrnPnl.add(scrn2);
mainScrnPnl.add(scrnBottom);
mainScrnPnl.add(winLose);

bottomPnl.setBackground(new Color(40,50,50));
bottomPnl.add(rollDiceBtn);
bottomPnl.add(playerStatusBar);
bottomPnl.add(placeBetBtn);
bottomPnl.add(newGameBtn);

// putting the pieces together

add(headPnl, BorderLayout.NORTH);
add(mainScrnPnl, BorderLayout.CENTER);
add(bottomPnl, BorderLayout.SOUTH);


} // end Craps() constructor



// ------------------------- METHODS -------------------------------------



public void newGame() { // begins a new game

currentMoney = initialMoney;
isGame = true;
startScreen();

} // end method newGame


public void startScreen() {

scrnBottom.setIcon(rolledIcons[0]);
winLose.setIcon(wonLostIcons[0]);

} // end method startScreen

public int getBet() { // gets the bet amt

betNumber = JOptionPane.showInputDialog("Enter Bet Amount:");
betAmt1 = Integer.parseInt( betNumber );
return betAmt1;

} // end method getBet

public void rollDice() { // at the moment just changes the pics

scrn1.setIcon(diceIcons[5]);
scrn2.setIcon(diceIcons[5]);

} // end method rollDice

// ------------------------ACTION EVENTS----------------------------------


public void actionPerformed(ActionEvent event) {


if (event.getSource() == placeBetBtn) {

betAmt = getBet();

}

if (event.getSource() == instructBtn) {

scrnBottom.setIcon(rolledIcons[8]);

}

if (event.getSource() == newGameBtn) {

newGame();

}

if (event.getSource() == rollDiceBtn) {

rollDice();

}


} // end actionperformed method

} // end CRAPS class
Who here knows java? I could use some help plzz Quote
Who here knows java? I could use some help plzz
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Who here knows java? I could use some help plzz
02-05-2010 , 02:03 PM
hey while im starting mine up, are u using an IDE ?

if not, u HAVE to use eclipse or netbeans (better for beginners) and use the debug function for this kinda stuff.

anyway brb
Who here knows java? I could use some help plzz Quote
02-05-2010 , 02:23 PM
well i noticed i dont have the images, so i cant run it quickly. but u should never do things like:

event.getSource() == placeBetBtn

do

event.getSource().equals(placeBetBtn)

instead. I dont know if this is the error here, maybe not. but always use equals if possible. what happens if you do a

System.out.println(event);

at the first line of the actionPerformed handler. event really not coming through ?

Another hint for bigger GUI's would be to do Swing updates over the Swing Eventthread, example:

SwingUtilites.invokeLater(new Runnable() {
public void run() {
somebutton.setIcon("icon");
});

yes, a lot more code, but u will run into problems sooner or later if u dont use this for ur GUI updates. Probably not really needed for ur project here and no solution for ur problem but i would have liked this info when i started java.

check if the actionperformed method gets called from ur clicks with the System.out.println, otherwise later i can make it run here too when i have more time
Who here knows java? I could use some help plzz Quote
02-05-2010 , 02:42 PM
Quote:
Originally Posted by Dropkick Brian
event.getSource() == placeBetBtn
do
event.getSource().equals(placeBetBtn)
instead. I dont know if this is the error here, maybe not. but always use equals if possible.
== will always do identity comparison, whereas equals() defaults to identity, but can be overridden to define a better comparision. For example
new String("1") == new String("1")
will always be false because they are different objects, but humans would expect them to be equivalent.

Stepping through your code with an IDE and printing log messages are essential to debugging you code. It helps you see what is really happening and not what you expect to be happening.
Who here knows java? I could use some help plzz Quote
02-05-2010 , 04:51 PM
Eclipse is effing garbage. So slow. Use IntelliJ instead.
Who here knows java? I could use some help plzz Quote
02-05-2010 , 11:01 PM
Morning from Australia, guys! Thanks for the replies!

I'm not using any IDE. In fact, I'm not really sure how an IDE works? Is it basically like dreamweaver, where u draw graphically what u want & it outputs the code? I will definately spend this arvo reading about netbeans & how it can help me!

The reason I'm assuming my button clicks are being consumed, is cuz I'm clicking the 'placeBetBtn' to test, & it should pop up a JOptionPane, but it's not doing anything. I wrote a similar program to test if the 'labels with Icons as the screen' was feasible, & the button clicks on that were working. But now that I've added a bit more complexity to my GUI something's gone awry

My parent's are coming over to check out my new apartment, but in a few hours I'll be diving back into my program. I will definately try out the event(placeBetBtn) to see if that solves the problem. Thanks for your help guys, will update soon (either another question or a working craps game for y'all)!!
Who here knows java? I could use some help plzz Quote
02-05-2010 , 11:34 PM
Quote:
Originally Posted by floppynutz
I'm not using any IDE. In fact, I'm not really sure how an IDE works? Is it basically like dreamweaver, where u draw graphically what u want & it outputs the code? I will definately spend this arvo reading about netbeans & how it can help me!
Integrated_ Development Environment - it's starts off as a text editor, but then goes on steroids for things that help programing the specific language easier. Some IDEs have GUI builders, some don't (Netbeans does). So the dreamweaver comparison does kind of hold, but think of it more about helping you code rather than being a WYSIWYG editor.

Quote:
Originally Posted by floppynutz
The reason I'm assuming my button clicks are being consumed, is cuz I'm clicking the 'placeBetBtn' to test, & it should pop up a JOptionPane, but it's not doing anything. I wrote a similar program to test if the 'labels with Icons as the screen' was feasible, & the button clicks on that were working. But now that I've added a bit more complexity to my GUI something's gone awry
Don't assume, find out exactly what it is doing. Stepping through the code with the IDE and making logging messages will help you see what is happening so you don't have to make assumptions.
Who here knows java? I could use some help plzz Quote
02-06-2010 , 02:46 AM
Ok, thanks again for your comments & time guys! Here's where I'm at now...

I think I get the idea of what you're saying. I need to put 'flags' in my program as System.out.println() to know what's happening when. So, I added one in the constructor, after I add all the JPanel's saying "you started the game"... It works, as I assumed it would cuz the game appears when I run the program. I also put 'flags' in the button actions, but as I feared, no msg shows up when u click the buttons. So it's 100% that my clicks are not being handled by my actionEvents method

So now I'm where I started. I guess the main question would be: Is it correct to handle my button clicks in the method like I have? I'm learning from a reference book, & just taking pieces of the different examples to create what I want. In another example, they create a private anonymous inner class to handle the button events? Actually, it's to handle a JTextField event, but perhaps this would work for buttons?

edit:

Also, I made the event.getSource().equals(placeBetBtn) changes as suggested, but it didn't make any difference. The comparison operator worked fine when I tried it on a more simple version of the game. In fact, the only difference that I can see between when the button clicks worked & now they don't, is that the mainScrnPnl is a little more complex. It has a few more JLabels attached to it, but that can't be why the button events are not being registered.

This has seriously stopped me dead for over a week

Last edited by floppynutz; 02-06-2010 at 02:55 AM.
Who here knows java? I could use some help plzz Quote
02-06-2010 , 09:34 AM
wow man it took me a long time to find the bug.

In your constructor you write:

// creating buttons, adding actionListeners
JButton newGameBtn = new JButton("new game");
newGameBtn.addActionListener(this);
JButton placeBetBtn = new JButton("place bet");
placeBetBtn.addActionListener(this);
JButton instructBtn = new JButton("instructions");
instructBtn.addActionListener(this);
JButton rollDiceBtn = new JButton(roll);
rollDiceBtn.addActionListener(this);

youre declaring new + only localbtns variables here. remove the bolded JButton stuff and it will work.

Last edited by Dropkick Brian; 02-06-2010 at 09:40 AM.
Who here knows java? I could use some help plzz Quote
02-06-2010 , 11:06 AM
Good catch, Dropkick.

For a style point, I generally create a unique anonymous action listener for each button. This allows you to organize the action functions more clearly and you don't have to do a long change of checking the source.
Who here knows java? I could use some help plzz Quote
Who here knows java? I could use some help plzz
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Who here knows java? I could use some help plzz

      
m