0

I am trying to import java.awt.*; into my class in Greenfoot but when I call a method, paintComponent(), I get an error saying that the method was not found.

The Greenfoot website states that native classes must be imported manually (http://www.greenfoot.org/doc/native_loader) and each native class must be included in my scenario (project).

The website gives a link to the native class loader but not the library containing the java.awt classes.

It would be great help if somebody could tell me where I can download the library or let me know if I am on the right track as I am completely new to Java.

Thanks

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.*;
import javax.swing.*;

public class Ground extends Actor
{
   public void act() {
      // Add your action code here.
   }

   public void paintComponent(Graphics z) {
      super.paintComponent(z);

      z.setColor(Color.BLUE);
      z.fillRect(0, 0, 100, 100);
   }
}
Shahmeer Navid
  • 566
  • 4
  • 10
  • 18
  • The java.awt package is a package of Java code - it's not native code (platform dependant code written in another language.) Thus you don't need to use the native loader at all! – Michael Berry Feb 29 '12 at 13:27

1 Answers1

1

paintComponent() is a method in Swing -- i.e., classes in package javax.swing. The classes in java.awt don't have such a method. It's introduced in javax.swing.JComponent, so all subclasses of JComponent -- i.e., JButton, JPanel, etc -- have it.

To draw a Greenfoot Actor, you create and return a GreenfootImage object. Here is its API. I think the correct equivalent to the above is something like

public class Ground extends Actor {
    public GreenfootImage getImage(){
        GreenfootImage image = new GreenfootImage(100, 100);
        image.setColor(Color.BLUE);
        image.fillRect(0, 0, 100, 100);
        return image;
    }
}

I don't know how often getImage() is called; maybe the Greenfoot documentation explains that.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • Unfortunately I also had import.javax.swing.*; in my code as well... I will post my entire code – Shahmeer Navid Feb 20 '12 at 04:41
  • Yes, but you still have to call the method on an instance of the correct class. You can only call `paintComponent()` on an instance of some class that has a method by that name -- i.e., on an instance of some type of `JComponent`. – Ernest Friedman-Hill Feb 20 '12 at 04:43
  • Understood. Do you have any recommendations as to how I can integrate this with Greenfoot? – Shahmeer Navid Feb 20 '12 at 04:45
  • Well, I don't know anything about Greenfoot, but I just Googled the Actor class, and I see you're supposed to return a `GreenfootImage` object to represent the actor. I will add some code to my answer to give you an idea of what you're supposed to do. – Ernest Friedman-Hill Feb 20 '12 at 04:49