Z
Z
zevilcube2019-08-30 21:22:29
Java
zevilcube, 2019-08-30 21:22:29

How to get all custom JComponents from a frame in Java?

I have my JComponent which is a picture:

public class JImage extends JComponent {

    private Image img = null;

    JImage () {
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(this.getImage(), 0, 0, this.getSize().width, this.getSize().height, null);
    }

    void setImage(String filePath) {
        try {
            this.img = ImageIO.read(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Image getImage() {
        return this.img;
    }
}


There is a class derived from JFrame with a mainPanel:

class Window extends JFrame {

    int width = 1000;
    int height = 500;
    private JPanel mainPanel;

    Window() {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLayout(null);
        setSize(width+5,height+28);
        setResizable(false);
        setLocation((screenSize.width-getWidth())/2, (screenSize.height-getHeight())/2);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        mainPanel = new JPanel();
        mainPanel.setBackground(Color.GREEN);
        mainPanel.setSize(getContentPane().getWidth(),getContentPane().getHeight());
        mainPanel.setVisible(true);

        add(mainPanel);

        repaint();
    }

    JPanel getMainPanel() {
        return mainPanel;
    }
}


I write main, display a window, add some JImages to mainPanel:

public static void main(String[] args) {
        Window window = new Window();

        JImage ji1 = new JImage();
        JImage ji2 = new JImage();
        JImage ji3 = new JImage();
        ji1.setImage("image1.png");
        ji2.setImage("image2.png");
        ji3.setImage("image3.png");
        window.getMainPanel().add(ji1);
        window.getMainPanel().add(ji2);
        window.getMainPanel().add(ji3);
       
    }


Now, how can I get all the components from mainPanel into an array, but so that they have a type not Component (as in mainPanel.getComponents()), but JImage?
If, for example, I need to change the image using setImage(""), then I can't do it, because the Component does not have this method

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question