My program code is here:
package Chapter12;
import java.awt.*;
import javax.swing.*;
public class Pv2 extends JPanel {
public static void main (String []args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
frame.setContentPane(new Pv2());
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
}
}
Eclipse shows this error when I’m trying to compile the code.
Cannot cast from Graphics to Graphics2D
This error occurs on this line :
Graphics2D g2 = (Graphics2D) g;
Tried jre 1.6 and jre 1.7 – the same thing. Why the cast isn’t allowed? I even tried to download some prepared codes and the error was the same.
You code is not broken and this cast is surely possible. The following code works:
One of the possible explanations, you have the class named exactly
GraphicsorGraphics2Din the same package (Chapter12). Then, with imports as you have, this class will have priority; if it is not compatible, the cast will be rejected by the compiler. I was able to reproduce this by crating the empty class in the same package and naming itGraphics2D.To solve, use explicit imports: replace your import statements by
This will tell the compiler which
GraphicsandGraphics2Ddo you mean. Even with confusingGraphics2Dclass, I do not longer see the error after rewriting imports as shown.