Reputation: 99
I am writing an applet that will randomly pick 10 cards and show them on the screen. However, I am receiving a .class error and a ; needed error when I attempt to pass an String[]. Anyone help? This is my code:
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
import java.applet.Applet;
import java.lang.Math;
import java.util.Random;
public class unit12Assignment extends Applet
{
Image card1 ... card52;
public void init()
{
card1 = getImage( getDocumentBase(), "c1.gif" );
...
card52 = getImage( getDocumentBase(), "sk.gif" );
}
public void getCards()
{
String cardNumber;
double cardRandom;
int cardRandomNumber;
String[] cardSelection = new String[10];
Random ran = new Random();
for (int number = 0; number <= 9; )
{
cardRandom = ran.nextInt(52) + 1;
cardRandomNumber = (int) Math.round( cardRandom );
if ( cardRandomNumber > 0 && cardRandomNumber <= 52 )
{
cardNumber = "card" + cardRandomNumber;
number++;
}
}
paint( String[] cardSelection );
}
public void paint(Graphics g, String[] card)
{
setBackground( Color.green );
g.drawImage( card[0], 10, 10, this);
g.drawImage( card[1], 90, 10, this);
g.drawImage( card[2], 170, 10, this);
g.drawImage( card[3], 250, 10, this);
}
}
Upvotes: 0
Views: 695
Reputation: 55233
This line:
paint( String[] cardSelection );
should syntactically be
paint( cardSelection );
You only need to write the type (for example String[]
) before a variable when you first declare it. From there it can just be referred to by its name.
I also notice that paint
takes a Graphics
argument as well as a String[]
, so you'll need to pass that in as well:
Graphics g = getGraphicsSomehow();
paint(g, cardSelection);
EDIT: see Andrew Thompson's answer for a disclaimer on using Graphics
with an alternative solution.
Upvotes: 2
Reputation: 168845
Anything involving getGraphics()
is a fragile solution.
If the user drags another another app. over the browser and covers the applet, then minimizes the other app., it is likely to erase the custom painted pixels. See Performing Custom Painting for how to paint correctly (which breaks down to 'paint when told to do so').
An alternative is to use a BufferedImage
for the rendering and display it in a JLabel
. Paint to the image whenever required, then repaint the label.
Upvotes: 1