当前位置:编程学习 > JAVA >>

关于空指针异常····求解决··在线等

--------------------编程问答-------------------- 瞎蒙一下:
在所有组件还没画出时,是不能获得Graphics的,只会返回空.只有在JFrame全部显示后才能get到Graphics. --------------------编程问答-------------------- 用paint(Graphics g){
 draw...
} --------------------编程问答-------------------- JPanel不是有void paintComponent(Graphics g)方法么。
这是我以前弄的一个绘图JPanel
class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D gps2D = (Graphics2D)g ;
//图形颜色
gps2D.setPaint(Color.BLACK);
//背景色
gps2D.setBackground(Color.BLUE);   //好像没成功
//绘制矩形
Rectangle2D r2d = new Rectangle2D.Double(leftX,topY,width,height);
gps2D.draw(r2d);
//绘制对角线
Line2D l2d = new Line2D.Double(leftX,topY,leftX+width,topY+height);
gps2D.draw(l2d);
//绘制椭圆
Ellipse2D e2d = new Ellipse2D.Double(leftX,topY,width,height);
gps2D.draw(e2d);
//绘制圆
double radius = Point2D.distance(leftX,topY,leftX+width,topY+height)/2;
double centX = r2d.getCenterX();
double centY = r2d.getCenterY();
Ellipse2D cyc = new Ellipse2D.Double();
cyc.setFrameFromCenter(centX,centY,centX+radius,centY+radius);
gps2D.setPaint(Color.LIGHT_GRAY);
gps2D.draw(cyc);
//图形填充
gps2D.setPaint(Color.LIGHT_GRAY);
gps2D.fill(cyc);
gps2D.setPaint(Color.BLACK);
gps2D.fill(r2d);
gps2D.setPaint(Color.GRAY);
gps2D.fill(e2d);
//设置字体
Font tempF = new Font("SansSerif",Font.BOLD,24);
gps2D.setFont(tempF);
String message = "Shape World";
FontRenderContext cont = gps2D.getFontRenderContext();
Rectangle2D rect = tempF.getStringBounds(message,cont);
//高度、宽度和上坡度
double sHeight = rect.getHeight();
double sWidth = rect.getWidth();
double ascent = -rect.getY();
LineMetrics lms = tempF.getLineMetrics(message,cont);
//下坡度和行间距
float descent = lms.getDescent();
float lead = lms.getLeading();
gps2D.drawString("Shape,World",225,50);
Rectangle2D rS2d = new Rectangle2D.Double(225,50-ascent,sWidth,sHeight);
gps2D.draw(rS2d);
Line2D lS2d = new Line2D.Double(225,50,225+sWidth,50);
gps2D.draw(lS2d);
Line2D lS2dd = new Line2D.Double(225,50+descent,225+sWidth,50+descent);
gps2D.draw(lS2dd);
}
public static final double leftX = 200;
public static final double topY = 150;
public static final double width =200;
public static final double height = 100;
}
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,