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);
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));
}
LAYOUT:
.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?