调整JFrame大小后,paintComponent中的图形会消失

时间:2012-02-11 11:37:41

标签: java swing resize jpanel paintcomponent

我是一名java初学者,&我正在创建一个使用箭头键绘制线条的程序,其中下一行从第一行的末尾开始。 现在,我创建了它,但问题是,每当我重新调整窗口大小时,绘图就会消失。

这是我的代码:

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();
    }
}    

1 个答案:

答案 0 :(得分:4)

paintComponent 应绘制组件的当前图形,而不仅仅是要添加的内容。因此,您现在有两种方法,要么记住所有行并将它们全部绘制出来,要么在生成行时创建一个单独的缓冲区,并在要求重绘时使用该缓冲区在组件上绘制。