java 如何在jpanel上画垂直线、水平线、平行线?

定义一个类继承JPanel类,重写 JPanel 的 paint 方法,使用 Graphics 绘制线段,如下代码:

import?java.awt.BorderLayout;

import?java.awt.Color;

import?java.awt.Graphics;

import?javax.swing.JFrame;

import?javax.swing.JPanel;

class?MyPanel?extends?JPanel?{

@Override

public?void?paint(Graphics?g)?{

super.paint(g);

g.setColor(Color.RED);

for?(int?i?=?0;?i?<?10;?i++)?{

g.drawLine(10,?10?+?i?*?20,?this.getWidth()?-?10,?10?+?i?*?20);

}

for?(int?i?=?0;?i?<?10;?i++)?{

g.drawLine(10?+?i?*?20,?10,?10?+?i?*?20,?this.getHeight()?-?10);

}

}

}

public?class?App?extends?JFrame?{

public?App()?{

this.setSize(400,?400);

this.setLocationRelativeTo(null);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyPanel?panel?=?new?MyPanel();

this.add(panel,?BorderLayout.CENTER);

}

public?static?void?main(String[]?args)?{

new?App().setVisible(true);

}

}

运行结果: