如何使用repaint()和revalidate()?

时间:2016-08-09 15:31:04

标签: java

我有这些功能,显示一组椅子,坐着和空,每2分钟按顺序改变,但是,每次我调用removeSeats()然后再调用displaySeats(),所有座椅组件似乎都消失了,但是我知道他们是他们的,因为我有另一个功能,可以查看每个主席的信息。

private void removeSeats(){

    for(int i = 0; i < c.getClassroom().size(); i++)
        pnlGame.remove(c.getClassroom().get(i).getSprite());

    for(int i = 0; i < emptySeats.size(); i++)
        pnlGame.remove(emptySeats.get(i).getSprite());

    pnlGame.repaint();
}

private void displaySeats(){
    // GAME SCREEN (pnlGame) Components

    emptySeats = new ArrayList<Sprite>();
    Sprite temp;
    int x = 25, y = 70, xS = 0, yS = 0, eI = 0, cI = 0;

    for(int i = 0; i < 64; i++){
        if(i % 8 == 0 && i != 0){
            x = 25;

            y += 80;
        }

        temp = new Sprite();
        temp.setName("Empty Seat");
        temp.getSprite().setBorder(BorderFactory.createLineBorder(Color.black));
        temp.setSprite(new JLabel(new ImageIcon("src\\seat.png")));
        temp.setOrigin(x, y);
        temp.setDimensions(40, 60);

        if(c.search(xS, yS) != null){
            if(c.getClassroom().get(cI).isPresent()){
                c.getClassroom().get(cI).getSprite().setBorder(BorderFactory.createLineBorder(Color.white));
                c.getClassroom().get(cI).setOrigin(x, y);
                c.getClassroom().get(cI).setDimensions(40, 60);
                pnlGame.add(c.getClassroom().get(cI).getSprite());

            }else{
                emptySeats.add(temp);
                pnlGame.add(emptySeats.get(eI).getSprite());
                eI++;
            }

            cI++;
        }else{
            emptySeats.add(temp);
            pnlGame.paintComponents(temp.getSprite().getGraphics());
            pnlGame.add(emptySeats.get(eI).getSprite());
            eI++;
        }

        xS++;
        if(xS >= 8){
            xS = 0;
            yS++;
        }

        x += 80;
    }

    pnlGame.revalidate();

}

1 个答案:

答案 0 :(得分:0)

我认为您需要在removeSeats方法中添加此行。

pnlGame.revalidate();
pnlGame.repaint();