我试图调整图标的大小,使其覆盖整个按钮并位于按钮中心。但是当我尝试时,它会拉伸我的按钮并破坏其他所有内容。我该怎么做?目前,我的代码如下:
在我的类构造函数中...
在我的类构造函数中...
javax.swing.JButton Console = new javax.swing.JButton;
ScaleButtonImage(Console, ConsoleEnabledImage);
Within that class..
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)
我将所有按钮水平和垂直链接在一起,使它们大小相同。
但实际上,结果看起来像下面这样。另外,如果我更改第一个按钮的图标,由于我的约束,所有按钮的大小都会改变。如何让图标适合按钮?