简体   繁体   English

Java初学者问题简单的图形

[英]Java Beginner Question simple Graphics

I'm getting an error saying that the methods are not applicable for the type Graphics? 我收到一个错误,说这些方法不适用于Graphics类型? I don't fully understand whats going on here - could anyone explain what I'm doing wrong and why its wrong? 我不完全了解这里发生了什么 - 有人能解释我做错了什么以及为什么错了? Thanks, 谢谢,

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Peach extends JPanel {
   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      this.setBackground(Color.WHITE);
      g.setColor(Color.BLUE);
      g.fillRect(25, 25, 100, 30);
      g.setColor(new Color(190, 82, 45));
      g.fillRect(25, 65, 100, 30);
      g.setColor(Color.RED);
      g.drawString("this is text", 25, 100);

   }
}

A guess: You've got another class that you've created in the same classpath called Graphics, and the compiler is confusing your class with the java.awt.Graphics class. 猜测:你已经在同一个名为Graphics的类路径中创建了另一个类,编译器使你的类与java.awt.Graphics类混淆。 If so, you could find out by using the fully qualified class name: 如果是这样,您可以通过使用完全限定的类名来找到:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Peach extends JPanel {
   public void paintComponent(java.awt.Graphics g) { // *** note change
      super.paintComponent(g);
      this.setBackground(Color.WHITE);
      g.setColor(Color.BLUE);
      g.fillRect(25, 25, 100, 30);
      g.setColor(new Color(190, 82, 45));
      g.fillRect(25, 65, 100, 30);
      g.setColor(Color.RED);
      g.drawString("this is text", 25, 100);

   }
}

And if so, then rename your own Graphics class to something else, say MyGraphics. 如果是这样,那么将你自己的Graphics类重命名为其他东西,比如MyGraphics。

But again, you'll want to post the actual error message (see comments above). 但同样,您需要发布实际的错误消息(请参阅上面的评论)。

So I had the exact same problem and what I had to do was copy all the code in the file that was giving me errors, delete that file, and paste my code into a new file and it started to work. 所以我遇到了完全相同的问题,而我要做的就是复制文件中的所有代码,这些代码会给我错误,删除该文件,然后将我的代码粘贴到一个新文件中,它就开始工作了。 That's how I got mine to work and I hope it works for you as well. 这就是我让我的工作方式,我希望它也适合你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM