21xrx.com
2025-03-29 06:22:04 Saturday
文章检索 我的文章 写文章
Java编写五角星和菱形代码
2023-06-18 13:52:48 深夜i     7     0
Java

Java语言的特性之一就是它的灵活性,可以用来编写各种各样的图形。本文将介绍如何使用Java编写五角星和菱形代码。

五角星代码:

import java.awt.*;
import javax.swing.*;
public class DrawStar extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g); //重写父类paintComponent方法
    int[] x = 109;
    int[] y = 54;
    g.drawPolygon(x, y, x.length);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.add(new DrawStar());
    f.setTitle("Five-pointed Star");
    f.setSize(120,120);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

菱形代码:

import java.awt.*;
import javax.swing.*;
public class DrawDiamond extends JPanel {
  public void paintComponent(Graphics g) {
    super.paintComponent(g); //重写父类paintComponent方法
    int[] x = 50;
    int[] y = 50;
    g.drawPolygon(x, y, x.length);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.add(new DrawDiamond());
    f.setTitle("Diamond");
    f.setSize(120,120);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

五角星, 菱形

  
  

评论区