Question

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);
   }
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top