简体   繁体   中英

Java Beginner Question simple Graphics

I'm getting an error saying that the methods are not applicable for the type 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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