如何在Visual Studio Code中用Java正确绘制牙买加国旗?
正确实现牙买加国旗绘制的Java代码
以下是符合要求的代码实现,严格遵循指定的导入结构,通过继承JComponent并重写paintComponent方法来绘制符合官方样式的牙买加国旗:
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.BasicStroke; import javax.swing.JComponent; import javax.swing.JFrame; public class JamaicaFlagComponent extends JComponent { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; int width = getWidth(); int height = getHeight(); int stripeWidth = width / 5; // 黄色条宽度为国旗宽度的1/5 // 牙买加国旗官方标准颜色 Color jamaicaGreen = new Color(0, 158, 73); Color jamaicaYellow = new Color(255, 212, 0); Color jamaicaBlack = new Color(0, 0, 0); // 绘制左上绿色三角形区域 g2d.setColor(jamaicaGreen); int[] greenTopLeftX = {0, width - stripeWidth, stripeWidth}; int[] greenTopLeftY = {0, 0, height}; g2d.fillPolygon(greenTopLeftX, greenTopLeftY, 3); // 绘制右下绿色三角形区域 int[] greenBottomRightX = {width, stripeWidth, width - stripeWidth}; int[] greenBottomRightY = {height, height, 0}; g2d.fillPolygon(greenBottomRightX, greenBottomRightY, 3); // 绘制右上黑色三角形区域 g2d.setColor(jamaicaBlack); int[] blackTopRightX = {width, stripeWidth, width - stripeWidth}; int[] blackTopRightY = {0, height, 0}; g2d.fillPolygon(blackTopRightX, blackTopRightY, 3); // 绘制左下黑色三角形区域 int[] blackBottomLeftX = {0, width - stripeWidth, stripeWidth}; int[] blackBottomLeftY = {height, 0, height}; g2d.fillPolygon(blackBottomLeftX, blackBottomLeftY, 3); // 绘制X形黄色宽条 g2d.setColor(jamaicaYellow); g2d.setStroke(new BasicStroke(stripeWidth)); g2d.drawLine(0, 0, width, height); g2d.drawLine(width, 0, 0, height); } public static void main(String[] args) { JFrame frame = new JFrame("牙买加国旗"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new JamaicaFlagComponent()); frame.setSize(600, 400); // 符合国旗2:3的长宽比例 frame.setVisible(true); } }
代码说明
- 颜色标准:使用牙买加国旗官方指定的RGB颜色值,确保视觉效果准确。
- 区域绘制:通过填充四个三角形来实现绿、黑交错的背景区域(左上、右下为绿色;右上、左下为黑色)。
- 黄色条绘制:将
Graphics转换为Graphics2D,通过BasicStroke设置线条宽度为国旗宽度的1/5,绘制两条对角线形成标志性的X形黄色宽条。 - 比例适配:窗口大小设置为600x400,严格遵循国旗2:3的长宽比例。
运行方式
在Visual Studio Code中,确保已配置好Java开发环境(JDK、Extension Pack for Java),直接运行该类的main方法即可看到正确的牙买加国旗效果。
内容的提问来源于stack exchange,提问作者user25019520
相关产品推荐
相关产品推荐

