import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Smile
{
private final int AREA_WIDTH = 500;
private final int AREA_HEIGHT = 400;
private final int FACE_SIZE = 200;
private int distance;
private JFrame jfSmile = new JFrame("给爷笑一个");
DrawCanvas drawArea = new DrawCanvas();
private void init()
{
drawArea.setPreferredSize(new Dimension(AREA_WIDTH,AREA_HEIGHT));
jfSmile.add(drawArea);
JButton jbtSmile = new JButton("笑的得瑟点");
jbtSmile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Timer timer = new Timer(100,new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
distance = distance > 0? 0 : 10;
drawArea.repaint();
}
});
timer.start();
}
});
JPanel jpButton = new JPanel();
jpButton.add(jbtSmile);
jfSmile.add(jpButton,BorderLayout.SOUTH);
drawArea.repaint();
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(jfSmile);
}
catch (Exception e)
{
e.printStackTrace();
}
jfSmile.pack();
jfSmile.setVisible(true);
jfSmile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class DrawCanvas extends JPanel
{
public void paint(Graphics g)
{
//背景变为白色
g.setColor(Color.WHITE);
g.fillRect(0,0,AREA_WIDTH,AREA_HEIGHT);
//绘制黄色大脸
g.setColor(Color.YELLOW);
g.fillOval((AREA_WIDTH-FACE_SIZE)/2,(AREA_HEIGHT-FACE_SIZE)/2+distance,FACE_SIZE,FACE_SIZE);
//用红色勾勒表情
g.setColor(Color.RED);
//眼部
g.drawArc((AREA_WIDTH-FACE_SIZE)/2+FACE_SIZE/8,AREA_HEIGHT/2-FACE_SIZE/4+distance,50,50,0,180);
g.drawArc((AREA_WIDTH)/2+FACE_SIZE/8,AREA_HEIGHT/2-FACE_SIZE/4+distance,50,50,0,180);
//画嘴
//直线是尝试出来的,最后+2属于微调
g.drawLine((AREA_WIDTH)/2-FACE_SIZE/4,AREA_HEIGHT/2+FACE_SIZE/16+2+distance,(AREA_WIDTH)/2-FACE_SIZE/4+100,AREA_HEIGHT/2+FACE_SIZE/16+2+distance);
//反向画圆弧注意:起点坐标是个矩形左上点。一个大矩形中包含一个整圆(或椭圆),看角度取其中一部分
//所以这时的高度比原先想的要高些。
g.drawArc((AREA_WIDTH)/2-FACE_SIZE/4,AREA_HEIGHT/2-FACE_SIZE/8+distance,100,80,0,-180);
}
}
public static void main(String[] args)
{
new Smile().init();
}
}
谨以此告诉自己,寻找编程中的快乐,而不是一味的盲目追求新技术,陷入无尽的自卑和痛苦中……小记