问题描述
publicUI(){setTitle("马周游问题");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(0,0,490,410);contentPane=newJPanel(newGridLayout());contentPane.setBorder(newEmptyBorder(5,5,5,5));setContentPane(contentPane);contentPane.setBackground(Color.WHITE);contentPane.setBounds(0,0,490,410);contentPane.setVisible(true);width=contentPane.getWidth();height=contentPane.getHeight();dLine=newDrawLine();dLine.draw(contentPane.getGraphics(),width,height);}publicvoiddraw(Graphicsg,intwidth,intheight){g.drawRect(10,10,width,height);//为什么这句说空指针异常啊?Graphics不是通过已经实例化了么?。}
另外我想问·在Jpanel上画图是怎样画的·用什么类什么函数··像drawLine()画完线怎么显示在面板上啊·是调用paint()还是repaint()还是直接通过getGraphics()返回到面板上的?比较乱不是很懂,麻烦大神解释下,帮助理清思路。。
解决方案
本帖最后由 q358543781 于 2013-12-23 15:40:05 编辑
解决方案二:
瞎蒙一下:在所有组件还没画出时,是不能获得Graphics的,只会返回空.只有在JFrame全部显示后才能get到Graphics.
解决方案三:
用paint(Graphicsg){draw...}
解决方案四:
JPanel不是有voidpaintComponent(Graphicsg)方法么。这是我以前弄的一个绘图JPanelclassMyPanelextendsJPanel{publicvoidpaintComponent(Graphicsg){super.paintComponent(g);Graphics2Dgps2D=(Graphics2D)g;//图形颜色gps2D.setPaint(Color.BLACK);//背景色gps2D.setBackground(Color.BLUE);//好像没成功//绘制矩形Rectangle2Dr2d=newRectangle2D.Double(leftX,topY,width,height);gps2D.draw(r2d);//绘制对角线Line2Dl2d=newLine2D.Double(leftX,topY,leftX+width,topY+height);gps2D.draw(l2d);//绘制椭圆Ellipse2De2d=newEllipse2D.Double(leftX,topY,width,height);gps2D.draw(e2d);//绘制圆doubleradius=Point2D.distance(leftX,topY,leftX+width,topY+height)/2;doublecentX=r2d.getCenterX();doublecentY=r2d.getCenterY();Ellipse2Dcyc=newEllipse2D.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);//设置字体FonttempF=newFont("SansSerif",Font.BOLD,24);gps2D.setFont(tempF);Stringmessage="ShapeWorld";FontRenderContextcont=gps2D.getFontRenderContext();Rectangle2Drect=tempF.getStringBounds(message,cont);//高度、宽度和上坡度doublesHeight=rect.getHeight();doublesWidth=rect.getWidth();doubleascent=-rect.getY();LineMetricslms=tempF.getLineMetrics(message,cont);//下坡度和行间距floatdescent=lms.getDescent();floatlead=lms.getLeading();gps2D.drawString("Shape,World",225,50);Rectangle2DrS2d=newRectangle2D.Double(225,50-ascent,sWidth,sHeight);gps2D.draw(rS2d);Line2DlS2d=newLine2D.Double(225,50,225+sWidth,50);gps2D.draw(lS2d);Line2DlS2dd=newLine2D.Double(225,50+descent,225+sWidth,50+descent);gps2D.draw(lS2dd);}publicstaticfinaldoubleleftX=200;publicstaticfinaldoubletopY=150;publicstaticfinaldoublewidth=200;publicstaticfinaldoubleheight=100;}