版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/86602077
程序功能:
使用Rectangle2D类draw方法绘制表格。
运行结果:
源码:
1. 测试类
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class DrawRectUsingRectangle2D {
static JTextArea statusBar = new JTextArea();
public static void main(String[] args)
{
// create a panel that contains our drawing
GridRectangle2DJPanel panel = new GridRectangle2DJPanel();
MouseHandler handler = new MouseHandler();
panel.addMouseMotionListener(handler);
// create a new frame to hold the panel
JFrame application = new JFrame();
application.setTitle("使用Rectangle2D.Double类绘制表格");
// set the frame to exit when it is closed
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel,BorderLayout.CENTER); // add the panel to the frame
application.add(statusBar,BorderLayout.SOUTH); // add the statusBar to the frame
application.setSize(280, 280); // set the size of the frame
application.setVisible(true); // make the frame visible
}
static class MouseHandler extends MouseMotionAdapter
{
// handle event when mouse enters area
@Override
public void mouseMoved(MouseEvent event)
{
statusBar.setText(String.format("光标当前坐标:[%d, %d]",
event.getX(), event.getY()));;
}
}
}
2. 实体类
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
/**
* 13.7 (Concentric Circles Using Class Ellipse2D.Double) Modify your solution
* to Exercise 13.6 to draw the ovals by using class Ellipse2D.Double and method
* draw of class Graphics2D.
* @author [email protected]
* @Date Jan 22, 2019, 1:44:03 PM
*
*/
public class GridRectangle2DJPanel extends JPanel
{
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
super.paintComponents(g);
double width = getWidth(); // total width
double height = getHeight(); // total height
int rRed;
int rGreen;
int rBlue;
int offset = 60; //10*10的表格,每个单元格边长10个像素,60为表格整体偏移量
//Color of arc, below color is called "Taibao Lan"
rRed = 21;
rGreen = 101;
rBlue = 192;
Color color=new Color(rRed, rGreen, rBlue);
//绘制1个10*10的表格
for (int i = 10; i > 0;i--){
for (int j = 10; j >0;j--) {
g2d.setColor(color);
g2d.draw(new Rectangle2D.Double(width/2-(j+1)*10+offset, height/2-(i+1)*10+offset, 10, 10));}
}
}
}