Java

打印空心菱形java怎么实现

小亿
85
2024-09-25 23:13:10
栏目: 编程语言

在Java中,你可以使用Java2D库来实现打印空心菱形。以下是一个简单的示例代码:

import javax.swing.*;
import java.awt.*;

public class DiamondPattern {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Diamond Pattern");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 400);
            frame.setLayout(new BorderLayout());

            JPanel panel = new JPanel() {
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                    int width = getWidth();
                    int height = getHeight();
                    int size = Math.min(width, height) / 2;

                    // Draw the upper and lower halves of the diamond
                    drawUpperHalf(g2d, width, height, size);
                    drawLowerHalf(g2d, width, height, size);
                }

                private void drawUpperHalf(Graphics2D g2d, int width, int height, int size) {
                    for (int i = 0; i < size; i++) {
                        int x = (width - size) / 2 + i;
                        int y = height / 2 - i;
                        g2d.fillOval(x, y, size, size);
                    }
                }

                private void drawLowerHalf(Graphics2D g2d, int width, int height, int size) {
                    for (int i = 0; i < size; i++) {
                        int x = (width - size) / 2 + i;
                        int y = height / 2 + i;
                        g2d.fillOval(x, y, size, size);
                    }
                }
            };

            frame.add(panel);
            frame.setVisible(true);
        });
    }
}

这个代码会创建一个窗口,并在其中绘制一个空心菱形。你可以根据需要调整窗口的大小或者使用不同的颜色。

0
看了该问题的人还看了