-3

I sound really silly for asking this, but I'm having trouble with my for loop.

Here is part of the code I'm having trouble with.

Scanner input = new Scanner( System.in);
int number;
for(int i = 0;i < 5;i++) {
  System.out.print("Enter 5 integers:");
  number = input.nextInt();
}

When I run it the print out loops more than 5 times.

public class BarGraph extends JPanel
{

    public void paintComponent( Graphics g )
    {

        Scanner input = new Scanner( System.in);
       // super.paintComponent(g);
        int number;

        for(int i = 0;i < 5;i++)
        {
             System.out.print("Enter 5 integers:");
        number = input.nextInt();
       // g.drawRect(10 * i, 10 * i, 100 * number, 10);    
        }
    }
}

Running BarGraphTest

public class BarGraphTest
{
    public static void main( String[] args)
    {
        BarGraph panel = new BarGraph();
        JFrame application = new JFrame();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        application.add( panel );
        application.setSize( 300, 300);
        application.setVisible( true );
    }
}

Basically what I'm trying to do is read 5 integers and just display them on JPanel line a bar graph.

user3485650
  • 29
  • 1
  • 4

1 Answers1

4

You have mixed up state change with graphics. paintComponent is called by swing "when it needs to be", in this case Swing determined it needed 2 repaints, for whatever reason.

If your program is written in a way that it cares when or how often paintComponent is called you will likely have problems. You should instead only have paintComponent ask about the current state of some object and paint accordingly.

Depepending on your exact circumstances the 5 numbers should be provided in one of the following ways

  • Passed to the constructor of BarGraph
  • Requested from the user in the constructor of BarGraph (not my favourite, but would work)
  • Passed to a method of BarGraph
  • Be in some other object that is passed to BarGraph.

They absolutely should not be requested from the user inside the paintComponent, this means that every time a redraw is nessissary (e.g. moving, re-sizing, changing focus, being hidden by other frames etc) the numbers will be re-requested from the user.

You are also likely to want to start your paintComponent method with super.paintComponent(g) but that will again be situation dependant

Community
  • 1
  • 1
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77