user1467401
user1467401

Reputation: 3

Java JFileChooser endless loop

When i am closing my JFileChooser dialog, it opens again. I'm using the libgdx update for checking the input.

Here is the input code...

if(!SaveDialog.open) {
    if(input.isKeyPressed(Input.Keys.S)) {
        SaveDialog.Save(pixmap);
    }
}

If I am pressing S very quickly, the dialog opens only one time, but if I am pressing it for like 2 sec, there will be a endless (I think) number of JFileChooser dialogs.

This is my code...

public class SaveDialog {
    private static boolean inited = false;
    private static JFileChooser fc;
    public static boolean open = false;

    public static void Init() {
        fc = new JFileChooser();

        fc.setFileFilter(new FileFilter() {
            public String getDescription() {
                return ".png";
            }
            public boolean accept(File f) {
                return f.getName().endsWith(".png");
            }
        });

        inited = true;
    }

    public static void Save(Pixmap pixmap) {
        open = true;

        if(!inited) {
            Init();
        }

        fc.showSaveDialog(null);

        byte[] data;
        try {
            data = PNG.toPNG(pixmap);
            FileHandle fh = new FileHandle(fc.getSelectedFile() + ".png");
            fh.writeBytes(data, false);
            open = false;
        }
        catch (IOException e) {
            open = false;
            e.printStackTrace();
        }
    }
}

Could someone please help me with this problem.

Upvotes: 0

Views: 327

Answers (1)

R Hyde
R Hyde

Reputation: 10409

It doesn't help that isKeyPressed(Input.Keys.S) determines if the S key is currently held down.

If you haven't given libgdx a chance to poll the input again before isKeyPressed() is called for the second time then I suspect that it will still think that it is held down.

If that isn't the issue, try recording the key's state and only open the dialog when it changes state from not pressed to pressed.

For example:

if(!SaveDialog.open) {
    boolean isSPressed = input.isKeyPressed(Input.Keys.S);
    if(!wasSpressed && isSPressed) {
        SaveDialog.Save(pixmap);
    }
    wasSPressed = isSPressed;
}

Upvotes: 1

Related Questions