gpt4 book ai didi

java - 为什么 .setColor(,,,) 说无法在此程序中找到符号?

转载 作者:行者123 更新时间:2023-12-02 06:05:59 26 4
gpt4 key购买 nike

当我运行此程序时,代码 g2.setColor(fillColor) 出现找不到符号错误。这是一个遗留问题吗?代码不正确?

I typed this code in verbatim from page165 of the book "Big Java" by Cay Horstmann

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

现在您可以在 paint 方法中使用 fillColor

关于java - 为什么 .setColor(,,,) 说无法在此程序中找到符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22291204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com