版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/86595703
程序功能:
显示8条线段(颜色随机,位置随机,线段粗度随机)。
运行结果:
源码:
1. 实体类
/**
* 13.8 (Random Lines Using Class Line2D.Double) Modify your solution to
* Exercise 13.7 to draw random lines in random colors and random thicknesses.
* Use class Line2D.Double and method draw of class Graphics2D to draw the
* lines.
*
* @author [email protected]
* @Date Jan 22, 2019, 1:44:03 PM
*
*/
public class RandomLinesJPanel 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=0;
int rGreen=0;
int rBlue=0;
final SecureRandom rn = new SecureRandom();
//画8个同心圆,每个同心圆相距10个像素
for (int i = 8; i > 0;i--){
//Color represented in RGB mode
rRed = rn.nextInt(256);
rGreen = rn.nextInt(256);
rBlue = rn.nextInt(256);
Color color=new Color(rRed, rGreen, rBlue);
g2d.setColor(color); //设置线段颜色
double startX = 1+width*rn.nextDouble();
double startY = 1+height*rn.nextDouble();
double endX = 1+width*rn.nextDouble();
double endY = 1+height*rn.nextDouble();
float thickness = (float) 1 + rn.nextInt(20);
g2d.setStroke(new BasicStroke(thickness)); //设置线段的粗细
g2d.draw(new Line2D.Double(startX, startY,
endX, endY)); //绘制线段
}
}
}
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 DrawRandomLines {
static JTextArea statusBar = new JTextArea();
public static void main(String[] args)
{
// create a panel that contains our drawing
RandomLinesJPanel panel = new RandomLinesJPanel();
MouseHandler handler = new MouseHandler();
panel.addMouseMotionListener(handler);
// create a new frame to hold the panel
JFrame application = new JFrame();
application.setTitle("使用Ellipse2D.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(460, 360); // 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()));;
}
}
}