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);
}
}