1

enter image description here

Code is :

 b1 = new JButton("1", new ImageIcon("C:\\Users\\29125\\Downloads\\IMG_7740.JPG"));

Is there a method I can use to make the image fit to the calculator rectangle shape perfectly?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Selina Gao
  • 11
  • 2
  • Rescale the image to the size of the JButton. – Gilbert Le Blanc Nov 29 '21 at 20:21
  • Does this answer your question? [Add a complex image in the panel, with buttons around it in one customized user interface](https://stackoverflow.com/questions/10861852/add-a-complex-image-in-the-panel-with-buttons-around-it-in-one-customized-user) – Andrew Thompson Nov 30 '21 at 16:57
  • 1
    Do not use file paths for application resources. By the time of deployment, these images will ***not*** be available as files, and must be accessed by URL. Use `getResource(..)` to form that URL. – Andrew Thompson Nov 30 '21 at 16:59

1 Answers1

0

Try this: create an Image, resize it to the size of the button, create the icon from this image and place it in the button, but all this only after displaying the frame.

Try this class

import java.awt.Dimension;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class TestImage {

    public static void main(String[] args) throws Exception {
        MyFrame f=new MyFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(600,600);
        f.show();
        f.setIcona();
    }
}

class MyFrame extends JFrame{
    private JPanel panel=new JPanel();
    private JButton button=new JButton();

    public MyFrame()throws Exception{
        getContentPane().add(panel);
        panel.add(button);
        //here you can set the size of your button, the photo will adapt (but if the aspect ratio is not right it also deforms)
        button.setPreferredSize(new Dimension(30,160));
    }

    public void setIcona() throws IOException{
        Image photo=ImageIO.read(new File("c:/Image.png"));
        image=photo.getScaledInstance(button.getWidth(), button.getHeight(), Image.SCALE_DEFAULT);
        ImageIcon icon=new ImageIcon(image);
        button.setIcon(icon);
        validate();
    }
}