Answer the question
In order to leave comments, you need to log in
Problems displaying custom JComponent. What to do?
I tried to create my own JImage class that inherits JComponent and contains an image. The application window starts, but the picture itself is not visible. Code below.
Main class:
public class Test {
public static void main(String[] args) {
Window window = new Window();
}
}
public class Window extends JFrame {
public Window() {
setSize(1000,500);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JImage img = new JImage();
img.setLayout(null);
img.setSize(100, 100);
img.setLocation(100,100);
img.setImage("img.png");
img.setVisible(true);
add(img);
}
}
public class JImage extends JComponent {
Image img;
public JImage () {}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(getImage(), getLocation().x, getLocation().y, getSize().width, getSize().height, null);
}
void setImage(String filePath) {
try {
this.img = ImageIO.read(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
Image getImage() {
return this.img;
}
}
Answer the question
In order to leave comments, you need to log in
added JLabel and ImageIcon between frame and jImage:
visible
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ImageEx extends JFrame {
public ImageEx() {
this.setLayout(new FlowLayout());
this.setSize(200, 200);
JLabel label = new JLabel();
JImage img = new JImage();
img.setImage("http://www.java2s.com/style/download.png");
label.setIcon(new ImageIcon(img.getImage()));
this.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class JImage extends JComponent {
BufferedImage img;
public JImage() {
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(getImage(), getLocation().x, getLocation().y, getSize().width,
getSize().height, null);
}
void setImage(String url) {
try {
this.img = ImageIO.read(new URL(url));
} catch (Exception e) {
e.printStackTrace();
}
}
BufferedImage getImage() {
return this.img;
}
}
public static void main(String avg[]) throws Exception {
ImageEx o = new ImageEx();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question