Search code examples
javaarraysswingjframejwindow

How to use JFrames or JWindows in an array


In my code I'm using over 100 predefined JWindows to play around with them over the screen : show or hide, move etc. The definition looks like :

    public static JWindow R2 = new JWindow();
    public static JWindow R3 = new JWindow();
    public static JWindow S2 = new JWindow();
    public static JWindow S3 = new JWindow();

    R2.getContentPane().add(s0.labelNow("/testingPackage/" + "R2" + ".jpg"));
    R2.pack();
    R2.setLocation(10, 350);
    R2.setVisible(true);
    R3.getContentPane().add(s0.labelNow("/testingPackage/" + "R3" + ".jpg"));
    R3.pack();
    R3.setLocation(40, 350);
    R3.setVisible(true);
    S2.getContentPane().add(s0.labelNow("/testingPackage/" + "S2" + ".jpg"));
    S2.pack();
    S2.setLocation(550, 750);
    S2.setVisible(true);   etc.

As you can see this is resulting in a real mess of code, so I wonder if I could put the JWindows in an array or something similar, so that I could use something like 'JWArray[4][50]' and use loops to declare, define, move, show, hide them ?

Please find code below where I try to use an array of JWindows, which results in a null pointer exception on the line "JWA[i].getContentPane().add". I assumed this JWA[] declaration must be wrong.

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;

public class ShowPicture3 extends JPanel {

public static JWindow[] JWA = new JWindow[5];
public static ShowPicture3 s0 = new ShowPicture3();

public JLabel labelNow(String path) {
    ImageIcon imgIcon = new ImageIcon(ShowPicture3.class.getResource(path));
    JLabel label = new JLabel(imgIcon);
    add(label);
    return label;
}

public void prepareImages() {
    for (int i = 0; i < 5; i++) {
        System.out.println("/testingPackage/" + "R" + (i + 2) + ".jpg");
        s0.labelNow("/testingPackage/" + "R" + (i + 2) + ".jpg");
        JWA[i].getContentPane().add(s0.labelNow("/testingPackage/" + "R" + (i + 2) + ".jpg"));
        JWA[i].pack();
        JWA[i].setLocation(10 + i * 20, 350);
        JWA[i].setVisible(true);
    }
}

public static void main(String[] args) throws Exception {
    s0.prepareImages();
    JWA[0].setLocation(100, 750);
    JWA[2].setVisible(false);
}

}

Solution

  • You forgot to initialize the JWA array contents (its filled with nulls by default), just add "JWA[i] = new JWindow();" like in the example below.

    public void prepareImages() {
        for (int i = 0; i < 5; i++) {
            JWA[i] = new JWindow();
            System.out.println("/testingPackage/" + "R" + (i + 2) + ".jpg");
            s0.labelNow("/testingPackage/" + "R" + (i + 2) + ".jpg");
            JWA[i].getContentPane().add(s0.labelNow("/testingPackage/" + "R" + (i + 2) + ".jpg"));
            JWA[i].pack();
            JWA[i].setLocation(10 + i * 20, 350);
            JWA[i].setVisible(true);
        }
    }