我想在Java中使用图像作为按钮,我试图这样做:
BufferedImage buttonIcon = ImageIO.read(new File("buttonIconPath"));
button = new JButton(new ImageIcon(buttonIcon));
Run Code Online (Sandbox Code Playgroud)
但这仍然显示图像背后的实际按钮,我只想将图像作为按钮,我该怎么做?
我正在尝试调整我的图标大小,使其覆盖整个按钮并位于按钮的中心.当我尝试时,它会拉伸我的按钮并弄乱其他所有东西.我该怎么做?目前,我的代码是:
在我的类的构造函数中..
javax.swing.JButton Console = new javax.swing.JButton;
ScaleButtonImage(Console, ConsoleEnabledImage);
Run Code Online (Sandbox Code Playgroud)
在那个班里..
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));
}
Run Code Online (Sandbox Code Playgroud)
布局:
.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, …Run Code Online (Sandbox Code Playgroud)