//**************************************************************************
// PP 6.11
//
// Design and implement a program that draws 20 horizontal, evenly spaced
// parallel lines of random length.
//**************************************************************************
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class PP6_11
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Lines");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
LinesPanel panel = new LinesPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
class LinesPanel extends JPanel
{
private final int WIDTH = 400,HEIGHT = 300, LENGTH = WIDTH / 2;
private final int SPACE = HEIGHT / 20, NUM_LINES = 20;
private Random generator;
我已经完成了任务,它工作得很好。编译运行时,代码画了 20 行,因为我使用了“SPACE”变量。我想知道是否有任何方法可以告诉程序我想通过使用“NUM_LINES”变量来绘制多少行。
//-----------------------------------------------------------------------
// Sets up the drawing panel.
//-----------------------------------------------------------------------
public LinesPanel()
{
generator = new Random();
setBackground (Color.black);
setPreferredSize (new Dimension (WIDTH, HEIGHT));
}
//-----------------------------------------------------------------------
// Paints evenly spaced Horizontal lines of random length.
// lines that are half the width are highlighted with a re color.
//-----------------------------------------------------------------------
public void paintComponent (Graphics page)
{
每次我尝试在 for 循环中使用 NUM_LINES = 20 和 SPACE = 20 变量时,它只画几行。这是我在 "for(int i = 0; i <= NUM_LINES; i += SPACE)" 之前使用的 for 循环
for (int i = 0; i <= HEIGHT; i += SPACE)
{
int y = generator.nextInt(WIDTH) + 1;
if (y <= LENGTH)
{
page.setColor(Color.red);
page.drawLine(0,i,y,i);
}
else
{
page.setColor(Color.blue);
page.drawLine (0,i,y,i);
}
}
}
}
有没有办法确定我画了多少条线并均匀地隔开它,或者我所做的方式是最好的方式?