1

所以这是类和超类,要遵循的问题:

测试图:

package project3;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class TestDraw extends MyShape
{
    public static void main(String[] args) 
    {
        DrawPanel panel = new DrawPanel();
        JFrame application = new JFrame();



        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.add(panel);
        application.setSize(300,300);
        application.setVisible(true);   
        JLabel southLabel = new JLabel(toString());
        application.add(southLabel, BorderLayout.SOUTH);
    }
}

我的形状:

package project3;

import java.awt.Color;

public class MyShape 
{
    private int x1, y1, x2, y2;
    private Color myColor;
    public MyShape()
    {
        setX1(1);
        setY1(1);
        setX2(1);
        setY2(1);
        setMyColor(Color.BLACK);
    }
    public MyShape(int x1, int y1, int x2, int y2, Color myColor)
    {
        setX1(x1);
        setY1(y1);
        setX2(x2);
        setY2(y2);
        setMyColor(myColor);
    }
    public void setX1(int x1)
    {
        if(x1 >= 0 && x1 <= 300)
        {
            this.x1 = x1;
        }
        else
        {
            this.x1 = 0;
        }
    }
    public int getX1()
    {
        return x1;
    }
    public void setY1(int y1)
    {
        if(y1 >= 0 && y1 <= 300)
        {
            this.y1 = y1;
        }
        else
        {
            this.y1 = 0;
        }
    }
    public int getY1()
    {
        return y1;
    }
    public void setX2(int x2)
    {
        if(x2 >= 0 && x2 <= 300)
        {
            this.x2 = x2;
        }
        else
        {
            this.x2 = 0;
        }
    }
    public int getX2()
    {
        return x2;
    }
    public void setY2(int y2)
    {
        if(y2 >= 0 && y2 <= 300)
        {
            this.y2 = y2;
        }
        else
        {
            this.y2 = 0;
        }
    }
    public int getY2()
    {
        return y2;
    }
    public void setMyColor(Color myColor)
    {
        this.myColor = myColor;
    }
    public Color getMyColor()
    {
        return myColor;
    }
    public String toString()
    {
        return String.format("X1: %d, X2: %d, Y1: %d, Y2: %d, Color: %s", getX1(), getX2(),
                getY1(), getY2(), getMyColor());
    }
}

在 TestDraw 类中,我试图将 MyShape 中的 toString 放入窗口上的文本框中,但是当我执行“JLabel southLabel = new JLabel(toString());”时 它告诉我的 toString() 需要是静态的。这一切都很好而且很花哨,除了当你让 toString 静态时,它想让那个字符串中的 get 成为静态的,这很糟糕......有什么想法吗?

我试过把 toString() 放在超类中,但它给出了同样的问题,试着问老师,但他说“看书”嗯……读了两个小时,我还没有找到我第三次通读后的一个例子。

先感谢您!

PS:答案很好,但最好解释一下!

4

2 回答 2

3

做一个你的类的实例。
TestDraw testDraw = new TestDraw();
并在其上调用 toString() 方法。在 main 方法中,您处于静态上下文中 - 也就是说,您没有 TestDraw 类型的对象,这也意味着您没有它的任何字段或方法。

于 2009-11-12T19:42:34.633 回答
1

这是因为您在静态方法(主要)中调用了非静态方法。那是行不通的。你需要做的是像这样实例化一个 TestDraw 对象:

TestDraw testDraw = new TestDraw();
JLabel southLabel = new JLabel(testDraw.toString());
于 2009-11-12T19:43:19.577 回答