在applet中绘制多行时,它只显示最后一行

时间:2016-01-06 23:48:39

标签: java swing canvas applet

我正在尝试使用Java applet和canvas绘制多行。我已经定义了类Canvas:

 public class Canvas extends JPanel {

    private static final int RIGHT=0, LEFT=1, UP=2, DOWN=3;
    public static final int WIDTH=600, HEIGHT=500;
    private int direction = 0 ;                          
    private int pixels;                             

    /**
     *  Canvas() constructor sets its size
     */
    public Canvas() {
        setSize(WIDTH, HEIGHT);
    }

    public void setPatt(int pat, int lev) {
        direction = pat;
        pixels = lev;
    }

    public void paintComponent(Graphics g) {
        g.setColor(getForeground());
        switch (direction) {
        case LEFT:  
            drawLineLeft(g, pixels); 
            break;
        case RIGHT:
            drawLineRight(g, pixels);
            break;
        case UP:
            drawLineUp(g, pixels);
            break;
        case DOWN:
            drawLineDown(g, pixels);
            break;
        } 
    } 

    private void drawLineLeft(Graphics g, int pix){

        if(pix > 0){
            Dimension d = getSize();
            int x = d.width/2;
            int y = d.height/2;
           g.drawLine(x, y, x-10*pix, y);//left
        }
    }

    private void drawLineUp(Graphics g, int pix){
        if(pix > 0){
            Dimension d = getSize();
            int x = d.width/2;
            int y = d.height/2;
            g.drawLine(x, y, x, y-10*pix);//up
        }
    }

    private void drawLineRight(Graphics g, int pix){
        //Graphics2D g2 = (Graphics2D) g;
        if(pix > 0){
            Dimension d = getSize();
            int x = d.width/2;
            int y = d.height/2;

            g.drawLine(x, y, x+10*pix, y);//right
        }
    }

    private void drawLineDown(Graphics g, int pix){
        if(pix > 0){
            Dimension d = getSize();
            int x = d.width/2;
            int y = d.height/2;
            g.drawLine(x, y, x, y+10*pix);// down
        }
    }
} 

我还有另一个类,我已经定义了下拉列表,文本字段和按钮。我可以从下拉列表中选择应该绘制线条的方向(向右,向左,向上,向下 - 方向),我可以通过在文本字段(像素)中键入数字来定义线条的长度。按下按钮时,将调用方法setPatt并在画布中显示行:

public class TurtleApplet extends JApplet implements ActionListener
{
    .....
    .....
    .....

    public void actionPerformed( ActionEvent e) 
    {
       if(e.getSource() == drawButton){
            int y = Integer.parseInt(pixels.getText());
            canvas.setPatt(direction.getSelectedIndex(), Integer.parseInt(pixels.getText()));

        }
       //repaint();
    }  
    .....
}

问题在于,当我按下按钮时,新行显示在画布中,然后当我调整applet窗口的大小时。我尝试添加repaint()方法,这有帮助,但还有另一个问题 - 如何在不丢失前一个的情况下绘制新线?

屏幕上只显示最后一行,例如,当我从中心向左画一条线(线总是从画布中心开始)然后我想从右边画一条新线中心,第一行第一行消失,我只能看到第二行,依此类推。

1 个答案:

答案 0 :(得分:0)

您应该跟踪已经绘制的线条。 paintComponent方法应该打印(或重新打印)整个组件。据我所知,你总是只打印1行,因此你松开了之前的状态。

尝试创建一个存储行数据的Map<Integer, Integer>,并在paintComponent方法中迭代以绘制所有行。

方法setPatt可能会被称为addPatt

PS:如果订单很重要,请尝试LinkedHashMap