Skip to main content

Graphics2D class

4 replies [Last post]
OnJava
Offline
Joined: 2006-02-14

I don't know what's going on with my compiler
When i call Graphics2D class in applications(not in applets), appears e message error: inconvertible types:
found: Graphics
required: Graphics2D
It's interesting, sometimes compiler founds errors sometimes not!
plz help someone

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
gfx
Offline
Joined: 2003-06-14

Can you show us some code where the compiler fails?

OnJava
Offline
Joined: 2006-02-14

Yes, here is a class that the compiler fails.

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

public class Graphics2D extends JPanel
{
public Graphics2D() {
JFrame korniza = new JFrame();
korniza.getContentPane().add(this);
korniza.setSize(400, 350);
korniza.setTitle("Graphics2D");
korniza.setVisible(true);
}

public void paint(Graphics g)
{ Graphics2D g2d = (Graphics2D) g; }

public static void main(String[] args) {
new Graphics2D(); }
}

gwampole
Offline
Joined: 2005-02-15

The problem occurs because your class is named [i]Graphics2D[/i]. In your [i]paint[/i] method, the compiler cannot determine whether you mean [i]java.awt.Graphics2D[/i] or your class: [i].Graphics2D[/i]. The solution is to fully qualify your references, like this:

[code]
import java.awt.*;
import javax.swing.*;

public class Graphics2D extends JPanel
{
public Graphics2D()
{
JFrame korniza = new JFrame();
korniza.getContentPane().add( this );
korniza.setSize( 400, 350 );
korniza.setTitle( "Graphics2D" );
korniza.setVisible( true );
}

public void paint( Graphics g )
{
java.awt.Graphics2D g2d = (java.awt.Graphics2D)g;
}

public static void main( String[] args )
{
new Graphics2D();
}
}
[/code]

Although, in practice, it's not generally a good idea to name your classes after another class in the Java class libraries that you plan to use, for this very reason.

OnJava
Offline
Joined: 2006-02-14

Thanks gwampole, I really appreciate your help! Now I get why compiler sometimes found errors sometimes not! Thanks again.