要求如题
代码如下:
SmileFace01:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class SmileFace01 extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth() / 2;
int height = getHeight() / 2;
// 绘制脸部
g.setColor(Color.YELLOW);
g.fillOval(100, 50, width, height);
// 绘制眼睛
g.setColor(Color.BLACK);
int eyeSize = width / 8;
int eyeY = height / 4 + 50;
g.fillOval(width / 4 - eyeSize / 2 + 100, eyeY, eyeSize, eyeSize);
g.fillOval(width * 3 / 4 - eyeSize / 2 + 100, eyeY, eyeSize, eyeSize);
// 绘制嘴巴
g.drawArc(135, 105, 120, 100, 0, -180);
}
}
SmileJFrame01:
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
public class SmileJFrame01 extends JFrame {
public SmileJFrame01() {
JFrame jFrame = new JFrame("Smile");
jFrame.setSize(400, 400);
jFrame.setLocation(400, 300);
jFrame.setDefaultCloseOperation(3);
// 添加文字
JLabel jLabel = new JLabel("Smiling...");
jLabel.setBounds(145, 260, 150, 20);
jLabel.setFont(new Font("宋体", Font.BOLD, 20));
jFrame.add(jLabel);
SmileFace01 panel = new SmileFace01();
jFrame.add(panel);
jFrame.setVisible(true);
}
}
SmileFace02:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class SmileFace02 extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth() / 2;
int height = getHeight() / 2;
// 绘制脸部
g.setColor(Color.YELLOW);
g.fillOval(100, 50, width, height);
// 绘制眼睛
g.setColor(Color.BLACK);
int eyeSize = width / 8;
int eyeY = height / 4 + 50;
g.fillOval(width / 4 - eyeSize / 2 + 100, eyeY, eyeSize, eyeSize);
g.fillOval(width * 3 / 4 - eyeSize / 2 + 100, eyeY, eyeSize, eyeSize);
// 绘制嘴巴
g.fillOval(135, 108, 120, 100);
g.setColor(Color.yellow);
g.fillOval(135, 107, 120, 90);
}
}
SmileJFrame02:
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
public class SmileJFrame02 extends JFrame {
public SmileJFrame02() {
JFrame jFrame = new JFrame("Smile");
jFrame.setSize(400, 400);
jFrame.setLocation(800, 300);
jFrame.setDefaultCloseOperation(3);
// 添加文字
JLabel jLabel = new JLabel("Smiling...");
jLabel.setBounds(145, 260, 150, 20);
jLabel.setFont(new Font("宋体", Font.BOLD, 20));
jFrame.add(jLabel);
SmileFace02 panel = new SmileFace02();
jFrame.add(panel);
jFrame.setVisible(true);
}
}
Test:
public class Test {
public static void main(String[] args) {
SmileJFrame01 frame01 = new SmileJFrame01();
SmileJFrame02 frame02 = new SmileJFrame02();
}
}
运行结果:
![](https://img-blog.csdnimg.cn/direct/ff290e873c28448bb0e01c3067c457b1.png)