mtheorylord mtheorylord - 1 month ago 9
Java Question

Removing element from array doesn't change graphic

In my application, I made an array to control the flag images in my output. This worked fine but when I remove an element from my array the picture doesn't change at all.

class Flag{

Image FlagImage;
int FlagNum = 0;

public Flag(int FlagNum) {
this.FlagNum = FlagNum;
try{
FlagImage = ImageIO.read(new File("flag1.png"));
}catch(Exception e){
}
}

public void Update() {

}

public void Draw(Graphics g) {
//Draw Flag
g.drawImage(FlagImage, ((FlagNum) % 3+1) * 100-100, (int)((FlagNum) / 3) * 100+100, null);
}

}
public class Flags extends JPanel {

/**
* Creates new form Flags
*/
public Flags(){
initComponents();
FlagSet.add(new Flag(1));
final Timer timer =new Timer(10, new ActionListener(){
@Override
public void actionPerformed(final ActionEvent e){
repaint();
for (Flag f: FlagSet){
f.Update();
}
}
});

}

public static ArrayList<Flag> FlagSet = new ArrayList();

@Override
public void paintComponent(Graphics g){

super.paintComponent(g);

for (Flag f: FlagSet){
f.Draw(g);

}
}


I then try to add flags like so:

flagCounter = 4;
while(flagCounter > -1){
Flags.FlagSet.add(new Flag(flagCounter));
flagCounter--;
}


Which works fine but my image doesn't change if I put in a
Flgas.FlageSet.remove(//Some flag)
later on. Any ideas? Thanks in advance.

Answer

It looks like you're missing a call to repaint().

Repaint is a signal sent to the drawing component to tell it that something has changed, and that it needs to call the paint methods again. In this case, as your addition to your Flags list will change how it is drawn, you should simply call repaint() after you've finished adding your flags.

Comments