Replace the varying element with a loop variable, e.g.
//you could probably also replace both instances of 800 here with a 'max' variable and the 100s with 'squareSize'
for (int i = 100; i<=800; i+=100)
{
paper.drawLine(i, 0, i, 800);
}
Explanation of the for loop
for ( A; B; C)
A
: Do this when you first get to the loop statement
B
: Check this is true, if it is, execute the loop
C
: Every time the loop executes, execute this afterwards.
So, we are setting i
to 100, executing the loop and adding 100 to i
. If i
goes over 800, continue past the loop.
Additionally
This is not a nice way to draw to the UI
Graphics paper = panel.getGraphics();
Have your panel @Override
the paint(Graphics g)
method and use the graphics object passed in there to do your drawing this means drawing is only done when the panel is drawn. Then just call repaint()
if you need to refresh it.
As well as that if you are messing with the GUI you should probably put it inside the EDT thread so as to avoid multiple threads doing graphic operations (as they can interfere)
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
//UI operations here
}
} );
This hands it off to a dedicated UI change thread queue.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…