Answer the question
In order to leave comments, you need to log in
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;
}
}
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;
}
}
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);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question