Home  >  Article  >  Java  >  How to set the size of button with picture in Java

How to set the size of button with picture in Java

王林
王林Original
2019-11-22 16:42:453086browse

How to set the size of button with picture in Java

In projects that require graphical interface programming in the Java part, image settings are often used to beautify buttons, but a very troublesome problem will arise during use. Follow the method:

JButton jb1 = new JButton();
jb1.setBounds(0, 0, 25, 20);
ImageIcon ii = new ImageIcon("images/xxx.png");
jb1.setIcon(ii);

At this point, you will find that the picture in the button does not fill the button as expected, but is placed in the button according to the size of the picture itself. So, what should be done to make the picture have the expected length and width of the button? What about the perfect filling in the button?

In fact, it is very simple. You only need to obtain the length and width of the set button in advance, use the getScaledInstance() method to reconstruct the image, and then construct the Icon object and pass it into the JButton.

The specific implementation process is as follows:

JButton jb1 = new JButton();
jb1.setBounds(0, 0, 25, 20);
ImageIcon ii = new ImageIcon("images/xxx.png");
//根据按钮大小改变图片大小
Image temp = ii.getImage().getScaledInstance(jb1.getWidth(), jb1.getHeight(), ii.getImage().SCALE_DEFAULT);
ii = new ImageIcon(temp);
jb1.setIcon(ii);

Recommended tutorial: java quick start

The above is the detailed content of How to set the size of button with picture in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn