版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/86601941
程序功能:
使用Graphics类drawRect方法绘制10*10表格。
运行结果:
源码:
1. 实体类
//Creating JFrame to display DrawPanel.
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
/**
* 13.13 (Grid Using Method drawRect) Write an application that draws a 10-by-10
* grid. Use the Graphics method drawRect.
*
* @author [email protected]
* @Date Jan 22, 2019, 20:34:03 PM
*
*/
public class GridDrawRectJPanel extends JPanel
{
public void paint(Graphics g)
{
super.paintComponents(g);
int width = getWidth(); // total width
int height = getHeight(); // total height
int rRed=0;
int rGreen=0;
int rBlue=0;
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--) {
g.setColor(color);
g.drawRect(width/2-(j+1)*10+offset, height/2-(i+1)*10+offset, 10, 10);}
}
}
}
2. 测试类
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class DrawGridUsingDrawRect {
static JTextArea statusBar = new JTextArea();
public static void main(String[] args)
{
// create a panel that contains our drawing
GridDrawRectJPanel panel = new GridDrawRectJPanel();
MouseHandler handler = new MouseHandler();
panel.addMouseMotionListener(handler);
// create a new frame to hold the panel
JFrame application = new JFrame();
application.setTitle("绘制表格");
// 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);
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()));;
}
}
}