在我的代码中,我使用了 100 多个预定义的 JWindows 在屏幕上玩弄它们:显示或隐藏、移动等。定义如下所示:
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.
正如您所看到的,这会导致代码非常混乱,所以我想知道是否可以将 JWindows 放在一个数组或类似的东西中,这样我就可以使用类似 'JWArray[4][50]' 的东西并使用循环来声明、定义、移动、显示、隐藏它们?
请在下面找到我尝试使用 JWindows 数组的代码,这会导致“JWA[i].getContentPane().add”行出现空指针异常。我认为这个 JWA[] 声明一定是错误的。
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);
}
}