在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);
});
}
}
這個代碼會創建一個窗口,并在其中繪制一個空心菱形。你可以根據需要調整窗口的大小或者使用不同的顏色。