I created a button that extends Jbutton, I added to the button image but this not render smooth the image. I try getScaledInstance
But it's not working
This is orginal image:
That's how it really presents the picture:
public class Button extends JButton {
private Image image;
public Button(Image image) {
this.image = image;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
Edit:
I understood why it not rendered smooth the image. I had to change the drawImage
to g.drawImage(image, 0, 0, null);
I run the code, sometimes it shows me the pictures and sometimes it shows me empty squares And that shows me errors in the console.
And only I move them with the mouse the pictures appear
Try the following. It is pretty self explanatory.
public class CircleDisplay extends JPanel {
final static int height = 500;
final static int width = 500;
Image img = null;
JFrame frame = new JFrame();
public static void main(String[] args) {
new CircleDisplay();
}
public CircleDisplay() {
Image img = null;
try {
img = ImageIO
.read(new File("f:yellowCircle.png"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.add(this);
img =
img.getScaledInstance(50, 50,
Image.SCALE_SMOOTH);
Button b = new Button(img);
b.setPreferredSize(new Dimension(50,50));
add(b);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Button extends JButton {
Image img;
public Button(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img,0,0,null);
}
}
I don't understand why it needs to be so complicated.
I suggest simply creating an ImageIcon
and setting the JButton
icon.
Sample code:
javax.swing.ImageIcon imgIco = new javax.swing.ImageIcon("path-to-icon-file");
javax.swing.JButton button2 = new javax.swing.JButton(imgIco);
button2.setPreferredSize(new java.awt.Dimension(imgIco.getIconWidth(), imgIco.getIconHeight()));
The last line of the above code ensures that the JButton
size is the same as the icon size, since you implied that this is what you want in your comment to the other answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.