Hi i am trying to initialize BufferedImage instance before constructor. is it possible ??
i don't know how & where ? i also don't want to initialize it in method or etc.
when i am trying ti initialize it before constructor it shows me an error.
my code :
public static class ImagePane extends JPanel
{
private BufferedImage bg;
java.util.List<Path> imageFiles= getFilesFromDirectory(FileSystems.getDefault().getPath("D:\\New folder"));
bg = ImageIO.read(new File((imageFiles.get(3)).toString()));
public ImagePane()
{
}
public void nextImage(int cnt)
{
}
}
i have also try to put bg initialization code inside a try-catch, but it shows an error.
Is this possible ?
You may use the initializer block.
Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
bg = ImageIO.read(new File((imageFiles.get(3)).toString()));
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
You can achieve this using the initializer block.
Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
public class ImagePane extends JPanel
{
private BufferedImage bg;
private java.util.List<Path> imageFiles;
{
imageFiles= getFilesFromDirectory(FileSystems.getDefault().getPath("D:\\New folder"));
bg = ImageIO.read(new File((imageFiles.get(3)).toString()));
}
public ImagePane()
{
}
public void nextImage(int cnt)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With