Java拉伸图标以适合按钮
我正在尝试调整图标的大小,以使其覆盖整个按钮并位于按钮的中央.当我尝试时,它会拉开我的按钮,并使其他所有内容弄乱.我该怎么做?目前,我的代码是:
I'm trying to resize my icon so that it covers the whole button and sits in the center of the button. When I try, it stretches my button and messes up everything else. How can I do it? Currently, my code is:
在我的类的构造函数中.
In my constructor of a class..
javax.swing.JButton Console = new javax.swing.JButton;
ScaleButtonImage(Console, ConsoleEnabledImage);
在那个班上..
private void ScaleButtonImage(javax.swing.JButton Button, java.awt.Image ButtonIcon) {
double Width = ButtonIcon.getWidth(Button);
double Height = ButtonIcon.getHeight(Button);
double xScale = 28/Width;//Button.getWidth() / Width;
double yScale = 28/Height;//Button.getHeight() / Height;
double Scale = Math.min(xScale, yScale); //ToFit
//double Scale = Math.max(xScale, yScale); //ToFill
java.awt.Image scaled = ButtonIcon.getScaledInstance((int)(Scale * Width), (int)(Scale * Height), java.awt.Image.SCALE_SMOOTH);
Button.setIcon(new javax.swing.ImageIcon(scaled));
}
布局:
.addGroup(layout.createSequentialGroup()
.addComponent(Enable, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Graphics, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Debug, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Console, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
然后我将它们全部水平和垂直地链接起来,以使它们的大小相同.
Then I link all of them horizontally and vertically so they're all the same size.
相反,它最终看起来像下面的样子.另外,如果我更改第一个按钮的图标,则由于我的限制,所有按钮的大小都会改变.如何使图标适合按钮?
Instead, it ends up looking like the below. Also, if I change the icon of the first button, all the buttons change size because of my constrains. How do I make the icons fit the buttons?
尝试类似的方法(如果我在方括号中没有记错的话):
Try something like this (If I didn't make any mistake with brackets):
JButton button = new JButton(new ImageIcon(((new ImageIcon(
"path-to-image").getImage()
.getScaledInstance(64, 64,
java.awt.Image.SCALE_SMOOTH)))));
这样,您的图片将被调整大小(在我的情况下为64x64大小)并添加到 button
中,如此处的示例所示:
This way your image will be resized (in my case to size 64x64) and added to button
, like in this example here:
这是调整图像大小并保持图像比例的方法:
This is the way to resize your image and to keep image ratio:
ImageIcon ii = new ImageIcon("path-to-image");
int scale = 2; // 2 times smaller
int width = ii.getIconWidth();
int newWidth = width / scale;
yourComponent.setIcon(new ImageIcon(ii.getImage().getScaledInstance(newWidth, -1,
java.awt.Image.SCALE_SMOOTH)));