我正在尝试调整我的图标大小,使其覆盖整个按钮并位于按钮的中心.当我尝试时,它会拉伸我的按钮并弄乱其他所有东西.我该怎么做?目前,我的代码是:
在我的类的构造函数中..
javax.swing.JButton Console = new javax.swing.JButton; ScaleButtonImage(Console,ConsoleEnabledImage);@H_502_5@在那个班里..
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)); }@H_502_5@布局:
.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) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Debug,javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Console,javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)@H_502_5@然后我将它们全部水平和垂直地连接起来,这样它们的大小都一样.
相反,它最终看起来像下面.此外,如果我更改第一个按钮的图标,由于我的约束,所有按钮都会改变大小.如何使图标适合按钮?
解决方法
尝试这样的事情(如果我没有用括号做错):
JButton button = new JButton(new ImageIcon(((new ImageIcon( "path-to-image").getImage() .getScaledInstance(64,64,java.awt.Image.SCALE_SMOOTH)))));@H_502_5@这样你的图像将被调整大小(在我的例子中大小为64×64)并添加到按钮,如下例所示:
编辑:
这是调整图像大小和保持图像比例的方法:
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)));@H_502_5@