Java:“非静态方法drawRect”错误

时间:2012-10-07 19:04:37

标签: java drawrect

我是Java的新手。以为我现在已经知道了一些东西,但我有一个问题证明不是这样!

确定!这里是。我有这段代码(编辑 - 非原创):

import java.util.*;
import java.awt.*;

public class MyClass extends HisClass
{
    public void drawRectangle(int width, int height)
    {
      int x1 = this.getXPos();
      int y1 = this.getYPos();
      java.awt.Graphics.drawRect(x1, y1, width, height);
    }

    public static void main(String[] args)
    {
      AnotherClass theOther = new AnotherClass();
      MyClass mine = new MyClass(theOther);
      mine.move();
    }
}

它给我的错误是:

MyClass.java:66: error: non-static method drawRect(int,int,int,int) cannot be referenced from a static context

你能帮我解决一下吗? 非常感谢。感谢。

2 个答案:

答案 0 :(得分:2)

java.awt.Graphics.drawRect(x1, y1, width, height);

drawRect方法不是静态的..您应该以某种方式获取Graphics类的实例: -

(graphicsInstance).drawRect(x1, y1, width, height);

由于Graphics类是abstract,所以你需要找到适当的方法来实例化你的Graphics对象,以获得graphicsInstance

您可以使用GraphicsContext绘制您想要的任何内容.. GraphicsContext是属于Graphics类的对象,您可以使用drawRect()

查看这些帖子。可能有用: -

How do I initialize a Graphics object in Java?

what is a graphics context (In Java)?

答案 1 :(得分:1)

以下是一些示例代码,通过覆盖Rectangle方法并将其添加到drawRect(),将JPanel paintComponent(Graphics g)用于JFrame。 / p>

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawRect extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //draw our rect
        g.setColor(Color.blue);
        g.drawRect(10, 10, 100, 50);
    }

    //or else we wont see the JPanel
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("DrawRect");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DrawRect());
        frame.pack();
        frame.setVisible(true);
    }
}