Home> Java> javaTutorial> body text

Write a function that generates heart-shaped patterns in Java language

PHPz
Release: 2024-01-11 12:18:34
Original
948 people have browsed it

Write a function that generates heart-shaped patterns in Java language

Java code example: drawing a heart-shaped pattern

import javax.swing.*; import java.awt.*; public class HeartPattern extends JFrame { public HeartPattern() { setTitle("Heart Pattern"); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.setStroke(new BasicStroke(3)); int x = getWidth() / 2; int y = getHeight() / 2; int radius = 100; // 绘制左半部分的心形 for (int i = -radius; i <= 0; i++) { double y1 = Math.sqrt(radius * radius - i * i); g2d.drawLine(x + i, y - (int) y1, x + i, y + (int) y1); } // 绘制右半部分的心形 for (int i = radius; i >= 0; i--) { double y1 = Math.sqrt(radius * radius - i * i); g2d.drawLine(x + i, y - (int) y1, x + i, y + (int) y1); } } public static void main(String[] args) { HeartPattern hp = new HeartPattern(); hp.setVisible(true); } }
Copy after login

This is a simple Java program that inherits the JFrame class and implements overriding the paint method to draw a heart shape pattern. The size of the form is set in the code, and the form is drawn by callingsuper.paint(g), and then theGraphics2Dobject g2d is used to draw the heart shape, and the color of the brush is set to Red, brush thickness is 3 pixels. Next, the abscissa x and ordinate y of the pattern center point are defined, and the radius of the heart-shaped drawing is set to 100. Then use a for loop to draw the left half of the heart, and the right half of the heart. Finally, create the HeartPattern object in the main method and set the form to be visible. After running the program, a form with a heart-shaped pattern will appear.

The above is the detailed content of Write a function that generates heart-shaped patterns in Java language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!