.class error in java applet

点点圈 提交于 2019-12-13 05:59:08

问题


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);
}

}


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12309220/class-error-in-java-applet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!