天天看點

Java開發GUI之圖形繪制

 在Java的GUI元件中,每一個視圖都有一個paint方法,這個方法負責元件的繪制,其中會傳入Graphics對象參數,開發者可以在paint方法中操作這個對象進行自定義圖形的繪制。示例如下:

class DrawPanel extends Panel{

private static final long serialVersionUID = 1L;

public DrawPanel() {

 super();

}

@Override

public void paint(Graphics g) {

 // TODO Auto-generated method stub

 super.paint(g);

 Color bg = Color.WHITE;

 Color fg = Color.RED;

 //繪制背景

 g.setColor(bg);

 g.draw3DRect(50, 50, 699, 140, true);

 g.draw3DRect(53, 53, 692, 133, true);

 g.setColor(fg);

 //繪制線

 g.drawLine(60, 60, 140, 60);

 //繪制矩形

 g.drawRect(150, 60, 80, 50);

 //繪制圓角矩形

 g.drawRoundRect(240, 60, 80, 50, 25, 25);

 //繪制橢圓

 g.drawOval(330, 60, 80, 50);

 //繪制弧線

 g.drawArc(420, 60, 50, 50, 0, 90);

 //繪制閉合折線

 Polygon polygon = new Polygon();

 polygon.addPoint(510, 60);

 polygon.addPoint(550, 60);

 polygon.addPoint(550, 110);

 polygon.addPoint(590, 110);

 g.drawPolygon(polygon);

 //填充矩形

 g.fillRect(600, 60, 80, 50);

 //填充3D矩形

 g.fill3DRect(60, 120, 80, 50, true);

 //填充圓角矩形

 g.fillRoundRect(150, 120, 80, 50, 25, 25);

 //填充橢圓

 g.fillOval(240, 120, 80, 50);

 //填充弧線

 g.fillArc(330, 120, 50, 50, 0, 90);

 //填充閉合折線

 Polygon polygon2 = new Polygon();

 polygon2.addPoint(390, 120);

 polygon2.addPoint(440, 120);

 polygon2.addPoint(440, 180);

 polygon2.addPoint(490, 180);

 g.fillPolygon(polygon2);

 //繪制文字

 g.drawString("finish draw test!", 500, 150);

}

效果如下圖:

Java開發GUI之圖形繪制