当我运行该程序时,代码g2.setColor(fillColor)出现找不到符号错误。这是一个遗留问题吗?代码不正确?
我从Cay Horstmann的“ Big Java”一书的第165页中逐字键入了此代码
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JOptionPane;
/**
* An applet that lets a user choose a color by specifying the fractions of
* red, green, and blue.
*/
public class ColorApplet extends Applet
{
public ColorApplet()
{
String input;
//Ask user for red, green, blue values
input = JOptionPane.showInputDialog("red: ");
float red = Float.parseFloat(input);
input = JOptionPane.showInputDialog("green: ");
float green = Float.parseFloat(input);
input = JOptionPane.showInputDialog("blue :");
float blue = Float.parseFloat(input);
//creates the color based on the RGB inputted values
Color fillColor= new Color(red, green, blue);
}
public void paint(Graphics g)
{
Graphics2D g2= (Graphics2D)g;
g2.setColor(fillColor);
Rectangle square = new Rectangle((getWidth() - SQUARE_LENGTH)/2,
(getHeight() - SQUARE_LENGTH)/2, SQUARE_LENGTH, SQUARE_LENGTH);
g2.fill(square);
}
private static final int SQUARE_LENGTH = 100;
}
最佳答案
fillColor
在paint
方法中未声明。在您的程序中,fillColor
仅在构造函数中具有作用域Color fillColor= new Color(red, green, blue);
您可以使其实例变量使其可访问,如下所示:
public class ColorApplet extends Applet
{
Color fillColor;
// now in constructor
public ColorApplet()
{
...
...
fillColor= new Color(red, green, blue);
}
现在您可以在
fillColor
方法中使用paint