日期:2014-05-20  浏览次数:21128 次

Graphics2D的问题,画不出东西
可以运行。
分2个文件。
下面是源代码,只有JFrame的框架,什么也没画出。

第一个文件ShapesJPanel.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BasicStroke;
import java.awt.GradientPaint;
import java.awt.TexturePaint;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Rectangle2D.Double;
import java.awt.geom.RoundRectangle2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class ShapesJPanel extends JPanel
{
public void paintComponet(Graphics g)
{
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setPaint(new GradientPaint(50,30,Color.BLUE,35,100,
Color.YELLOW,true));
g2d.fill(new Ellipse2D.Double(500,30,65,100));

g2d.setPaint(Color.RED);
g2d.setStroke(new BasicStroke(10.0f));
g2d.draw(new Rectangle2D.Double(80,30,65,100));

BufferedImage buffImage = new BufferedImage(10,10,
BufferedImage.TYPE_INT_RGB);

Graphics2D gg = buffImage.createGraphics();
gg.setColor(Color.YELLOW);
gg.fillRect(0, 0, 10, 10);
gg.setColor(Color.BLACK);
gg.drawRect(1,1,6,6);
gg.setColor(Color.BLUE);
gg.fillRect(1, 1, 3, 3);
gg.setColor(Color.RED);
gg.fillRect(4, 4, 3, 3);

g2d.setPaint(new TexturePaint(buffImage,
new Rectangle(10,10)));
g2d.fill(
new RoundRectangle2D.Double(155,30,75,100,50,50));

g2d.setPaint(Color.WHITE);
g2d.setStroke(new BasicStroke(6.0f));
g2d.draw(new Arc2D.Double(240,30,75,100,0,270,Arc2D.PIE));

g2d.setPaint(Color.GREEN);
g2d.draw(new Line2D.Double(395,30,320,150));



}
}

--------------
第二个文件:Shapes.java,包含main 方法。
import javax.swing.JFrame;

public class Shapes
{

public static void main(String[] args)
{

JFrame frame = new JFrame("Drawing 2D shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ShapesJPanel shapesJPanel = new ShapesJPanel();

frame.add(shapesJPanel);
frame.setSize(1024,1024);
frame.setVisible(true);
}
}

--------------
这个Graphics2D 的g2d,gg对象都不起作用啊,哪错了啊?

------解决方案--------------------
paintComponet -> paintComponent

加了 @Override 的话你自己就能发现。