I’m a java beginner, & I’m creating a program that draws lines using the arrow keys, where the next line starts from the end of the first line.
Now, I created it, but the problem is that, whenever I re-size the window, the drawing disappears.
Here is my code:
public class draw extends JPanel {
int up = 1, down = 0, left = 0, right = 0;
int beginX, beginY;
@Override
public void paintComponent(Graphics g) {
if(up == 1){
beginX = getWidth() / 2;
beginY = getHeight() / 2;
}
if (up > 0) {
g.drawLine(beginX, beginY, (beginX), (beginY - up));
beginY -= (up);
up = 0;
} else if (down > 0) {
g.drawLine(beginX, beginY, beginX, (beginY + down));
beginY += down;
down = 0;
} else if (right > 0) {
g.drawLine(beginX, beginY, (beginX + right), beginY);
beginX += right;
right = 0;
} else if (left > 0) {
g.drawLine(beginX, beginY, (beginX - left), beginY);
beginX -= (left);
left = 0;
}
}
public void drawUp() {
up += 3;
repaint();
}
public void drawDown() {
down += 3;
repaint();
}
public void drawLeft() {
left += 3;
repaint();
}
public void drawRight() {
right += 3;
repaint();
}
}
The paintComponent should draw the current graphics of the component, not just what you want to add. So you now have two approaches, either to remember all lines and draw them all, or create a separate buffer to draw on as you generate the lines and use that buffer to draw on the component when it asks to be redrawn.