Is there a way to determine the exact amount of lines you want to draw on a page using for loops?

StackOverflow https://stackoverflow.com/questions/17508250

문제

//**************************************************************************
// 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;

I have completed the assignment and it works just fine. When compiled and run, the code draws 20 lines because I use the "SPACE" variable. I would like to know if there is any way I could tell the program how many lines I would like for it to draw just by using the "NUM_LINES" variable.

    //-----------------------------------------------------------------------
    // 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)
    {

Every time I try to use the NUM_LINES = 20 and SPACE = 20 variables in the for loop, it only draws a few lines. Here's the for loop I was using before "for(int i = 0; i <= NUM_LINES; i += 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);
            }
        }


    }



}

Is there a way to determine how many lines I draw AND evenly space it or is the way I've done it the best way to do it?

도움이 되었습니까?

해결책

The simple answer is to change your for loop to:

for (int i = 0; i < HEIGHT; i += (HEIGHT - 1) / (NUM_LINES - 1))

Note that I've changed the comparison to exclude the equals (since HEIGHT is actually outside your window) and we dynamically calculate the distance between the lines.

The subtraction from HEIGHT corrects for the fact that our lines are in a zero-based coordinate system. The subtraction from NUM_LINES adjusts for the fact that the first line is drawn at zero. Note that your solution doesn't account for this last factor, but happens to "work" because you draw the last line off screen. If you changed your HEIGHT to 401, you'd actually see 21 lines.

Here is a better implementation that accounts for a number of factors, such as redrawing odd multiples of height and line spacing, and actual panel sizing. It also centers the lines vertically to be more aesthetically pleasing.

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(20, 0.5);
        panel.setPreferredSize (new Dimension (400, 300));

        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

class LinesPanel extends JPanel
{
    private final int numLines;
    private final double colorSplit;
    private final Random generator;

    //-----------------------------------------------------------------------
    // Sets up the drawing panel.
    //-----------------------------------------------------------------------

    public LinesPanel(int numLines, double colorSplit)
    {
        this.numLines = numLines;
        this.colorSplit = colorSplit;

        this.generator = new Random();

        setBackground (Color.black);
    }

    //-----------------------------------------------------------------------
    // 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)
    {
        // Clear the off-screen bitmap and set the background.
        super.paintComponent(page);

        final int pageWidth = getWidth();
        final int pageHeight = getHeight();

        // Calculate the line spacing and center vertically.
        final int lineSpace = (pageHeight - 1) / (numLines - 1);
        final int margin = (pageHeight - (lineSpace * (numLines - 1))) / 2;

            final int splitWidth = (int)(pageWidth * colorSplit);

        for (int y = margin; y < pageHeight; y += lineSpace)
        {
            int width = generator.nextInt(pageWidth) + 1;
            page.setColor(width <= splitWidth ? Color.red : Color.blue);
            page.drawLine(0, y, width, y);
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top