一個簡答的笑臉。
需要兩個java文件
代碼如下:
GradeBook.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class GradeBook extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
/*
* fillOval方法用來畫橢圓, 四個參數分別是:
* x the x coordinate of the upper left cornerof the oval to be filled. X軸座標
* y the y coordinate of the upper left corner of the oval to be filled. Y軸座標
* width the width of the oval to be filled. 寬度
* height the height of the oval to be filled. 高度
*/
// 畫臉
g.setColor(Color.YELLOW);
g.fillOval(10, 10, 200, 200);
// 畫兩個眼睛
g.setColor(Color.BLACK);
g.fillOval(55, 64, 30, 30);
g.fillOval(135, 64, 30, 30);
// 畫嘴巴
g.fillOval(50, 110, 120, 60);
// 嘴巴露出微笑
g.setColor(Color.YELLOW);
g.fillOval(50, 110, 120, 30);
g.fillOval(50, 120, 120, 40);
}
}
另一個java文件:GradeBookTest.java
import javax.swing.JFrame;
public class GradeBookTest {
// 程序的入口點
public static void main(String[] args) {
// 實例化GradeBook
GradeBook myGradeBook = new GradeBook();
// 實例化JFrame來當畫板撒
JFrame application = new JFrame();
// 退出應用程序默認的窗口關閉操作
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 將要畫的玩意兒添加到畫板去
application.add(myGradeBook);
// 設置畫板的大小
application.setSize(230, 250);
// 畫板是否可見
application.setVisible(true);
}
}
運行效果如下圖: