ошибка несовместимых типов в Java со строками и текстом - PullRequest
0 голосов
/ 12 октября 2018

Я пытаюсь создать метод установки для метки, но продолжаю получать одну и ту же ошибку, после попытки нескольких решений, которые я придумала, я все еще не могу понять, почему то, что я делаю, неправильно.Я продолжаю получать эту ошибку: «несовместимые типы: java.lang.string не может быть преобразован в текст».Это мой полный код:

    public class Bar {
    // the numeric value of the bar
    private int value;
    // the rectangle representing the bar
    private Rectangle view;
    // The text label for this bar
    private Text label;
    // The value as a text object
    private Text valueText;

    /**
     * Constructor for a bar object.  The rectangle for the bar is
     * also constructed here and its size is set to the given height.
     * The value of the bar is initialised to 0.
     * If there is a label for the bar, a Text object is created using the 
     * text of the label and the colour of the label set to black.
     * The bar and the label are not visible until the display method
     * is called.
     *
     * @param label The label for the bar.
     * @param width The height of the bar.
     */
    public Bar(java.lang.String label, int height) {
        value = 0;
        view = new Rectangle();
        view.changeSize(0, height);
        this.label = new Text(label);

    }
    public void display() {
        view.makeVisible();
        label.makeVisible();
    }

    public int setValue(int val) {
        this.value = val;
        return val;
    }

    public int getValue() {
        return value;

    }

    public Rectangle getView() {
        return view;
    }

    public void setLabel(java.lang.String text) {
        label  = text;
    }

    public Text getLabel() {
        return label;
    }

    public void setColor(java.lang.String color) {
        view.changeColor(color);
    }

    public java.lang.String getColors() {
        return view.getColorName();
    }

    public void setPosition(int x, int y) {
        label.setPosition(x,y);

    }

}

Это исходный код текстового класса:

import acm.graphics.GLabel;
import java.awt.GraphicsEnvironment;

/**
* Write a description of class Text here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Text extends Drawable
{
private String fontName = "arial";
private String fontStyle = "plain";
private int fontSize = 18;

/**
 * Constructor for objects of class Text
 */
public Text(String text)
{
    // initialise instance variables
    object = new GLabel(text);
    this.setFill(false);
    changeColor("black");
    ((GLabel)object).setFont(createFont());
    add(((GLabel)object));
    setLocation(100, 200);
    markAsComplete();
}

private String createFont() {
    StringBuffer sb = new StringBuffer();
    sb.append(fontName);
    sb.append("-");
    sb.append(fontStyle);
    sb.append("-");
    sb.append(fontSize);
    return sb.toString();
}

public void setText(String newText) {
    ((GLabel)object).setLabel(newText);
}

/**
 * Change the font size of the text to a given value. The value of newSize
 * must be >= 0.
 * 
 * @param newSize
 *            the new font size of the text.
 */
public void changeSize(int newSize) {
    this.fontSize = newSize;
    ((GLabel)object).setFont(createFont());
}

/**
 * Print the names of all the available fonts.
 */
public void printFonts() {
    GraphicsEnvironment ge = GraphicsEnvironment
        .getLocalGraphicsEnvironment();
    String[] names = ge.getAvailableFontFamilyNames();
    for (String name : names) {
        System.out.println(name);
    }
}

/**
 * The name of the current font.
 */
public String getFontName() {
    return ((GLabel)object).getFont().getFontName();
}

/**
 * Find the width of the text in the selected font.
 * 
 * @return the width of the text
 */
public int getTextWidth() {
    return (int) ((GLabel)object).getWidth();
}

/**
 * Find the height of the text in the selected font.
 * 
 * @return the height of the text
 */
public int getTextHeight() {
    return (int) ((GLabel)object).getHeight(); 
}

public String getText() {
    return ((GLabel)object).getLabel();
}

}

1 Ответ

0 голосов
/ 12 октября 2018

В вашем установщике setLabel() вы пытаетесь присвоить ссылку на объект типа String полю label типа Text, и компилятор сообщает, что это невозможно.

Вы можете исправить это так же, как вы делаете это в конструкторе:

public void setLabel(java.lang.String text) {
  label  = new Text(text);
}

Обратите внимание, что установщик должен принять объект Text в качестве параметра, поэтому вы можете подумать об изменении его на setLabel(Text text)и затем использовать его со строкой таким образом: yourObject.setLabel(new Text("yourStringLabel")).

...