Hi - Im making a small and relatively simple game that use's the common feature of the scoreboard to keep track of the user's score. I have declared the main game frame in one class, the actual game on one panel in another and have decided to keep the scoreboard as a class of its own.
When I want to update the score using the scoreboard class I can - but when I try to do the same thing using the same methods outlined in the scoreboard class it doesn't work. I create an instance of the class as you would and have added a few lines to determine whether or not the method was being called - it was. So why wouldn't it update the way it does in the other class.
The scoreboard class is as follows:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
public class scoreBoard extends JPanel
{
int userScore = 0;
String text = "Score: "+userScore;
int posX = 10; int posY = 25;
JButton changeText = new JButton("Update Score");
public scoreBoard()
{
changeText.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
text = "Score: "+increaseScore();
/**
posX += 5;
posY += 10;
*/
repaint();
}
});
add( changeText );
setBackground( Color.RED );
}
public void paint(Graphics g)
{
super.paint( g ); // Over-ride the paint method
Graphics2D g2score = ( Graphics2D )g;
g2score.drawString( text, posX, posY );
}
public int increaseScore()
{
userScore += 10;
return userScore;
}
}
***Please excuse the randomness of some of the colours :P***
Second class called MPanel - I have only included the relevant method & the code which creates the instance here:
scoreBoard keepScore = new scoreBoard();
/*************************************************/
public JButton createJButton( int buttonNum )
{
// final int rand = getRandomNum(4);
/**
Check the random numbers are generated
System.out.println( rand );
*/
// Button becomes a constant
final JButton button = new JButton();
button.setText(""+buttonNum );
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if( button.getText().contains("1") || button.getText().contains("2") )
{
System.out.println( "BOOM" );
keepScore.text = "Score: "+keepScore.increaseScore();
keepScore.repaint();
button.setIcon( bomb );
}
}
});
return button;
}
So what you think?