Java 1.0 Applet -- 不兼容的类型:无法将选择转换为按钮 -- Java 简而言之示例 1-2

Java 1.0 Applet -- Incompatible Types: Choice cannot be converted to Button -- Java In A Nutshell Example 1-2

我正在尝试从处理 Java 1.0 的 Java In A Nutshell Book 中编译示例 1-2。我收到一条错误消息,指出无法将选择转换为按钮。现在,我不知道这是否是当前 Java 不支持我正在调用的库的问题,或者某些东西已关闭。

小程序应该是一种绘图板,错误在第 14 行 / clear_button = new Choice();

import java.applet.*;
import java.awt.*;

public class Scribble extends Applet {
    private int last_x = 0;
    private int last_y = 0;
    private Color current_color = Color.black;
    private Button clear_button;
    private Choice color_choices;

public void init(){
    this.setBackground(Color.white);

    clear_button = new Choice();
    clear_button.setForeground(Color.black);
    clear_button.setBackground(Color.lightGray);
    this.add(clear_button);

    color_choices = new Choice();
    color_choices.addItem("black");
    color_choices.addItem("red");
    color_choices.addItem("yellow");
    color_choices.addItem("green");
    color_choices.setForeground(Color.black);
    color_choices.setBackground(Color.lightGray);
    this.add(new Label("Color: "));
    this.add(color_choices);
}

public boolean mouseDown(Event e, int x, int y){
    last_x = x; last_y = y;
    return true;
}

public boolean mouseDrag(Event e, int x, int y){
    Graphics g = this.setGraphics();
    g.setColor(current_color);
    g.drawline(last_x, last_y, x, y);
    last_x = x;
    last_y = y;
    return true;
}

public boolean action(Event event, Object arg) {
    if (event.target == clear_button) {
        Graphics g = this.getGraphics();
        Rectangle r = this.bounds();
        g.setColor(this.getBackground());
        g.fillRect(r.x, r.y, r.width, r.height);
        return true;
    }

    else if (event.target == color.choices) {
        if (arg.equals("black")) current_color = color.black;
        else if (arg.equals("red")) current_color = color.red;
        else if (arg.equals("yellow")) current_color = color.yellow;
        else if (arg.equals("green")) current_color = color.green;
        return true;
    }

    else return super.action(event, arg);

 }
}

这是因为 Choice 不是从 Button 扩展而来的。类型不兼容。

https://docs.oracle.com/javase/7/docs/api/java/awt/Choice.html

为了解决这个问题,您需要像这样将 clear_button 的类型更改为 Choice:

private Choice clear_button;

我刚刚检查了旧的 java 1.0.2 文档,那里的 Choice 也没有从 Button 扩展:

http://web.mit.edu/java_v1.0.2/www/javadoc/java.awt.Choice.html#top

根据您的评论 this.setGraphics() 在 Java 1.0.2 和现代 Java.

中都不存在

根据您的代码判断,您应该将其替换为 this.getGraphics()。

获取图形处理程序的另一种方法是覆盖:

public void paint(Graphics g)

您可以在 class 中覆盖此方法。