lundi 16 mars 2015

My program keeps generating four times?

For some reason when i run this program instead of outputting one card choice I get 3, sometimes four.


I'm trying to pick a name from the array list include it in the path, then output the image, you can see the result with the system out.


Heres the code:



public class Main {

public static void main (String[] args) {

Main.createScreen();

}

public static void createScreen() {

JFrame p = new JFrame("Angora Realms");
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameGUI g = new GameGUI();
p.add(g);
p.setLocationRelativeTo(null);
p.pack();
p.setVisible(true);

}
}


Here's where i create the GUI and also the paint:



@SuppressWarnings("serial")
public class GameGUI extends JPanel implements ActionListener {

public Button drawCard = new Button("Draw Card");

public GameGUI() {
drawCard.addActionListener(this);
add(drawCard);
}

@Override
public void actionPerformed(ActionEvent event) {

Object cause = event.getSource();

if (cause == drawCard) {
System.out.println("Ay");
repaint();
}
}


@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
Cards c = new Cards();
g.drawImage(c.getImage(), 0, 0, 450, 700, this);
}
}


And here is where i choose what card to load:



public class Cards {

static Random random = new Random();

public static String getCard() {

String card = null;
String[] possibleCards = new String[] {"Cheetah", "Lion"};

card = possibleCards[random.nextInt(2)];
System.out.println(card);

return card;

}

public Image getImage() {

Image img = null;

try {
img = ImageIO.read(getClass().getResource("/dev/angora/images/plains/" + Cards.getCard() + ".png"));
}
catch (IOException e) {
e.printStackTrace();
}

return img;
}

}


When I run the code I get 4 system print outs of a random variation of Cheetah and Lion. I've been told before that I'm actually creating 3 instances of my code somewhere, but I have no idea where...


Aucun commentaire:

Enregistrer un commentaire