如何从getTextWidth方法返回的值中获取变量?

时间:2018-10-13 18:44:33

标签: java bluej

我正在为学校作业制作一张条形图。但是,当尝试将条形标签放置在条形左侧时,我卡住了。我假设我必须使用一种方法来获取标签文本的宽度,然后从条形图的x位置减去该值。

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(String label, int height) {

        view = new Rectangle();
        view.changeSize (0,height);
        this.label = new Text(label);
        display();
    }

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

    public void setValue (int Newvalue){
        value= Newvalue;
    }

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

    public int getTextWidth() {
        return (int) ((Text)label).getWidth();

    }
}

编辑: 到目前为止,我已经附上了我的BlueJ程序的屏幕快照以及作业说明。 bar chart assignment 我已经在Public calss栏中创建了一个名为“ view”的矩形矩形。矩形的(条形)宽度最初设置为零,这就是为什么画布上显示为一条线(参见图片)的原因。我创建了一个标签为“文本”,每次编辑宽度时,该标签都必须出现在条(我的矩形)的左侧。关键是我不知道如何编辑方法Public void set value中的width。当我调用该方法并输入100作为参数值时,条形图的值应更改为100,视图的宽度(矩形)应更改为100,但没有变化。并且标签位置错误。在setPosition方法中,我必须使标签显示在矩形(栏)的左侧。但是如何?然后,当我调用显示方法时,我必须在cavas上看到代表条形宽度的值。怎么样?非常感谢。

请注意,我是一个绝对的初学者,距离课程只有3周了。

所以基本上,我希望getTextWidth()返回的值从条的x坐标中减去(文本必须出现在条的左侧)。非常感谢您的帮助。

0 个答案:

没有答案
相关问题