使用 Java 绘制小鸟和柱子模型代码示例

本文提供 Java 代码示例,展示如何使用 Java 绘制简单的小鸟和柱子模型。代码示例包含图形绘制、颜色设置、坐标定位等基本操作,适合初学者学习 Java 图形编程。

小鸟模型

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Bird extends JPanel {

    private static final long serialVersionUID = 1L;

    private int x;
    private int y;
    private int width;
    private int height;

    public Bird(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.YELLOW);
        g.fillOval(x, y, width, height);
        g.setColor(Color.BLACK);
        g.drawOval(x, y, width, height);
        g.drawLine(x + width / 2, y + height / 2, x + width / 2 + width / 4, y + height / 2);
        g.drawArc(x + width / 4, y + height / 4, width / 2, height / 2, -45, -90);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame('Bird Model');
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        Bird bird = new Bird(150, 150, 50, 50);
        frame.add(bird);
        frame.setVisible(true);
    }
}

柱子模型

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Column extends JPanel {

    private static final long serialVersionUID = 1L;

    private int x;
    private int y;
    private int width;
    private int height;

    public Column(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        g.fillRect(x, y, width, height);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, width, height);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame('Column Model');
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        Column column = new Column(150, 150, 50, 200);
        frame.add(column);
        frame.setVisible(true);
    }
}

说明:

  • 代码示例使用 Java Swing 库绘制图形。
  • 小鸟模型使用 fillOval() 方法绘制黄色圆形,并使用 drawOval() 方法绘制黑色边框,最后使用 drawLine()drawArc() 方法绘制小鸟的翅膀和嘴巴。
  • 柱子模型使用 fillRect() 方法绘制绿色矩形,并使用 drawRect() 方法绘制黑色边框。
  • 可以根据需要修改代码中颜色、大小、位置等参数,创建不同样式的小鸟和柱子模型。
Java 绘制小鸟和柱子模型代码示例

原文地址: https://www.cveoy.top/t/topic/ndjN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录