Reputation: 1475
I've been looking all over the internet for a solution of how to add components over image. I've tried this:
setContentPane(new JComponent(){
@Override
protected void paintComponent(Graphics g){
URL url = ...;
if(url==null){
//... Irelevant
return;
}
try {
BufferedImage img = ImageIO.read(url);
g.drawImage(img,0 ,0, this);
super.paintComponents(g);
} catch (IOException e) {
//... Irelevant
e.printStackTrace();
return;
}
}
});
nameLabel=new JLabel("<html><body>"+Main.translateColorsToHTML(name)+"</body></html>");
nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
nameLabel.setVisible(true);
add(nameLabel);
Which didn't work, so I've tried this:
URL url = ...;//Fetching the url
if(url==null){
//... Unrelevant
return;
}
try {
BufferedImage img = ImageIO.read(url);
invImg = new JLabel(new ImageIcon(img));
invImg.setMaximumSize(new Dimension(340, 250));
setContentPane(invImg);
} catch (IOException e) {
e.printStackTrace();
return;
}
And then adding a component to the content pane / the frame itself. I have absoloutly no idea how to do this, any help will be appreciated. Thanks in advance!
Upvotes: 0
Views: 108
Reputation: 299
Hey mind to add a jPanel
on your JFrame
? (It is almost always a better idea)
Add a jPanel
on your JFrame
, and draw on it.
Override
the paint(Graphics2D g)
method of jPanel
(inherited from JComponent
) and draw your image like this
yourPanel = new javax.swing.JPanel(){
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(yourImage, null, x, y);
}
}
Upvotes: 0
Reputation: 1475
I found a solution which works just fine:
BufferedImage img = ImageIO.read(url);
invImg = new JLabel();
invImg.setIcon(new ImageIcon(img));
invImg.setLayout(new BoxLayout(invImg, BoxLayout.Y_AXIS));
setContentPane(invImg);
Upvotes: 1