java 绘制长方形_java 画矩形

这篇博客展示了如何在Java中使用Swing组件来绘制一个由星号(*)组成的矩形。通过创建`StarRectangle`类,设置等宽字体并利用`Graphics`对象的`drawChars`方法,实现了在特定位置绘制不同高度的星号矩形。
摘要由CSDN通过智能技术生成

package org.zergle.test.swing;

import java.awt.Font;

import java.awt.FontMetrics;

import java.awt.Graphics;

import java.awt.Point;

import java.util.Arrays;

import javax.swing.JFrame;

import javax.swing.JPanel;

/**

* 星号组成的矩形

*

* @author Johnson Lee

*

*/

public class StarRectangle {

private Point location;

private int width;

private int height;

public StarRectangle(Point location, int width, int height) {

this.location = location;

this.width = width;

this.height = height;

}

/**

* 绘制自己

*

* @param g

*/

public void draw(Graphics g) {

char[] top = new char[width];

char[] mid = new char[width];

Arrays.fill(top, '*');

Arrays.fill(mid, ' ');

mid[0] = '*';

mid[mid.length - 1] = '*';

Font font = g.getFont();

// 设置字体为等宽字体

g.setFont(new Font("Courier New", Font.PLAIN, 10));

FontMetrics fm = g.getFontMetrics();

int x = location.x;

int y = location.y;

int h = fm.getHeight();

g.drawChars(top, 0, top.length, x, y);

if (this.height >= 2) {

y += h;

for (int i = 0; i < this.height - 2; i++) {

g.drawChars(mid, 0, mid.length, x, y);

y += h;

}

g.drawChars(top, 0, top.length, x, y);

}

g.setFont(font);

}

/**

* @param args

*/

public static void main(String[] args) {

new Canvas();

}

}

/**

* 画布

*

* @author Johnson Lee

*

*/

class Canvas extends JFrame {

public Canvas() {

this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

this.setContentPane(new JPanel() {

public void paint(Graphics g) {

new StarRectangle(new Point(130, 100), 50, 5).draw(g);

}

});

this.setSize(600, 400);

this.setVisible(true);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值