我正在尝试调整图标的大小,使其覆盖整个按钮并位于按钮的中心。当我尝试时,它会拉伸我的按钮并弄乱其他一切。我该怎么做?目前,我的代码是:
在我的类的构造函数中..
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)
然后我将它们水平和垂直连接起来,使它们都具有相同的大小。
相反,它最终看起来像下面这样。此外,如果我更改第一个按钮的图标,所有按钮都会因为我的限制而改变大小。如何使图标适合按钮?