//**************************************************************************
// 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」變量繪製多少行。有沒有一種方法可以確定要使用for循環在頁面上繪製的線的確切數量?
//-----------------------------------------------------------------------
// 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)
{
每次我嘗試使用NUM_LINES = 20和空間= 20個變量在for循環中,只汲取幾行。這裏的for循環我用之前 「的for(int i = 0;我< = NUM_LINES;我+ = SPACE)」
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);
}
}
}
}
有沒有一種方法,以確定有多少行繪製和均勻地間隔開,或我做到這一點的最好方法是什麼?