Reputation: 41
So i have a class that extends JLabel that I am using as a button (using the clicklistener class) and I am trying to add a background image to the label (see below) but when i use this label the text is off to the right of the image. is there a way to use the image as an actual background? i would like to avoid making a separate image for each button.
public class DButton
extends JLabel
{
URL imgPath;
ImageIcon img;
public DButton(int width, int height)
{
this.setOpaque(true);
imgPath = getClass().getResource("/img/MainMenuButton.png");
if(imgPath != null)
{
img = new ImageIcon(imgPath);
this.setIcon(img);
}else
{
System.err.println("Cant find file");
}
}
public DButton(int width, int height, String text)
{
this(width, height);
this.setText(text);
}
}
edit: Thanks everyone for the quick responses, i got it figured out (setting the vertical and horizontal alignments)
Upvotes: 0
Views: 527
Reputation: 12463
You need to override the paint method of your label:
@Override
protected void paintComponent(Graphics g) {
g.drawImage(imgPath, 0, 0, this);
super.paintComponent(g);
}
Upvotes: 1
Reputation: 347244
Why not just adjust the vertical and horizontal properties of the label?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BackgroundLabel {
public static void main(String[] args) {
new BackgroundLabel();
}
public BackgroundLabel() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new FlowLayout(FlowLayout.CENTER));
try {
BufferedImage icon = ImageIO.read(new File("Pony.png"));
JLabel label = new JLabel("Flying Ponies");
label.setIcon(new ImageIcon(icon));
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
add(label);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Upvotes: 2
Reputation: 3028
At
img = new ImageIcon(imgPath);
try this
image = img.getImage()
graphics = image.getGraphics()
graphics.drawString("Text", 0, 0)
Upvotes: 1