Is there a way to add a JLabel from a class to another CardLayout?

36 Views Asked by At

I'm doing a project for school and my goal here is to design a gallery on Swing. One of the features is the possibility to add new images to my gallery and display the new picture. I created a card where you can add your picture by browsing the file explorer on your computer and then it will copy and add the file to the folder of the app. For the moment this part works fine, but when I go back to my GalleryPage CardLayout the image is not displayed (because I don't know how to add it directly). What I'm trying to do is add this new image to the bottomPanel of my GalleryPage java class from newImg [JLabel] on my NewImage java class. Is there a way to do that? I've been browsing the Internet to find an answer but I can't find a solution.

Here is my code:

Gallery.java

public class Gallery extends JPanel {
    private GalleryPage panelGalleryPage;
    private NewImage newImage;
    protected static CardLayout cardGal;

    public Gallery() {
        super();
        setLayout(new CardLayout());
        cardGal = (CardLayout) this.getLayout();
        panelGalleryPage = new GalleryPage();
        newImage = new NewImage();
        add(panelGalleryPage, "GalleryPage");
        add(newImage, "NewImage");
    }
}

GalleryPage.java

public class GalleryPage extends JPanel {

    // preparing my grid of images by sorting the filepath of each image.
    File directory = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images");

    int fileCount = directory.list().length;
    private JButton addImg, delImg;
    private JLabel title;
    private JLabel[] cache = new JLabel[fileCount];
    private ImageIcon[] imgGrid = new ImageIcon[fileCount];
    private ImageIcon imgTitle, imgAdd, imgDel;
    private JSplitPane splitPanel;
    private JPanel bottomPanel, topPanel;
    private List<String> results;

    public GalleryPage() {
        super();
        setBackground(PowerOn.userInterface.DARK_GREY);
        initComponents();
    }

    public void initComponents() {

        // create a split pane
        splitPanel = new JSplitPane();

        topPanel = new JPanel(); // top component
        bottomPanel = new JPanel(); // bottom component

        // configure splitPanel
        splitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
        splitPanel.setDividerLocation(100);
        splitPanel.setDividerSize(0);
        splitPanel.setTopComponent(topPanel);
        splitPanel.setBottomComponent(bottomPanel);

        // create title
        imgTitle = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/images.png");
        imgTitle.setImage(imgTitle.getImage().getScaledInstance(80, 80, Image.SCALE_DEFAULT));
        title = new JLabel(imgTitle);

        // create add Button
        imgAdd = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/add.png");
        imgAdd.setImage(imgAdd.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        addImg = new JButton(imgAdd);
        addImg.setPreferredSize(new Dimension(60, 40));

        // add Actionlisteneer to addImg Button
        addImg.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Gallery.cardGal.show(PowerOn.gallery, "NewImage");
            }
        });

        // create delete Button
        imgDel = new ImageIcon("oop_2022/src/main/java/com/phone/common/png/trash.png");
        imgDel.setImage(imgDel.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        delImg = new JButton(imgDel);
        delImg.setPreferredSize(new Dimension(60, 40));

        // Add title and buttons to the topPanel
        topPanel.add(title);
        topPanel.add(addImg);
        topPanel.add(delImg);

        // add the splitPanel to the frame
        this.add(splitPanel);

        // set top and bottom panel Background
        topPanel.setBackground(PowerOn.userInterface.DARK_GREY);
        bottomPanel.setBackground(PowerOn.userInterface.DARK_GREY);

        // set a GridLayout for the bottomPanel
        this.setLayout(new GridLayout());
        GridLayout layout = new GridLayout(0, 3, 10, 10);
        bottomPanel.setLayout(layout);

        // creating an array of file
        results = new ArrayList<String>();
        File[] files = new File("oop_2022/src/main/java/com/phone/common/png/Galery_images").listFiles();

        // retrieving the name of each images
        for (File file : files) {
            if (file.isFile()) {
                results.add(file.getName());
            }
        }

        // create an array of images
        for (int i = 0; i < fileCount; i++) {
            imgGrid[i] = new ImageIcon(files[i].toString());
        }

        // loop to sale and add the images to the bottomPanel
        for (int i = 0; i < files.length; i++) {
            // scaling the images
            imgGrid[i].setImage(imgGrid[i].getImage().getScaledInstance(120, 120,
                    Image.SCALE_SMOOTH));

            // add the images to the grid
            cache[i] = new JLabel(imgGrid[i]);
            bottomPanel.add(cache[i]);
        }
    }
}

NewImage.java

public class NewImage extends JPanel {
    private JLabel title, newImg;
    private ImageIcon cacheImg;
    private JPanel display;
    private JButton choose, back;
    private JFileChooser file;
    private File selectedFile;
    private Gallery addNew;

    public NewImage() {
        super();
        setBackground(PowerOn.userInterface.DARK_GREY);
        initComponents();
    }

    public void initComponents() {

        // configure title JLabel
        title = new JLabel("Choose a new image to add (jpg or png only)");
        title.setHorizontalAlignment(title.CENTER);

        // configurin choose JButton + Actionlistener
        choose = new JButton("Explore");
        file = new JFileChooser();
        choose.setPreferredSize(new Dimension(60, 60));
        choose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                int result = file.showOpenDialog(display);
                if (result == JFileChooser.APPROVE_OPTION) {
                    selectedFile = file.getSelectedFile();

                    // check the type of the file only jpg and png accepted
                    String check = selectedFile.getAbsolutePath()
                            .substring(selectedFile.getAbsolutePath().length() - 3);
                    System.out.println(check);

                    // if the fil is ok add the file to the gallery directory
                    if (check.equals("png") || check.equals("jpg")) {

                        // retrieving the name of the file and copy on the galery folder
                        try {
                            String[] parts = selectedFile.getAbsolutePath().split(Pattern.quote(File.separator));
                            String dest = "oop_2022/src/main/java/com/phone/common/png/Galery_images/"
                                    + parts[parts.length - 1];
                            copyFile(selectedFile, new File(dest));
                            cacheImg = new ImageIcon(dest);
                            cacheImg.setImage(cacheImg.getImage().getScaledInstance(120, 120, Image.SCALE_DEFAULT));
                            newImg = new JLabel(cacheImg);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        JOptionPane.showMessageDialog(null, "Your image as been succesfully uploaded");
                    }

                    // if the file is not a png or a jpg display an error message
                    else {
                        JOptionPane.showMessageDialog(null, "You must choose a png or jpg file");
                    }
                }
            }
        });

        // configuring back JButton + Actionlistener
        back = new JButton("Return to home page");
        back.setPreferredSize(new Dimension(60, 60));
        back.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Gallery.cardGal.show(PowerOn.gallery, "GalleryPage");
            }
        });

        // configure layout of panel
        this.setLayout(new GridLayout());

        // add panels
        display = new JPanel();
        display.setLayout(new GridLayout(0, 1));
        this.add(display);
        display.add(title);
        display.add(choose);
        display.add(back);
    }

    public static void copyFile(File from, File to) throws IOException {
        Files.copy(from.toPath(), new FileOutputStream(to));
    }
}

What I want is that the image I added is directly displayed without running the code again when I go back to my gallery page.

my gallery page

0

There are 0 best solutions below