我有一个swing应用程序,我想在jbutton上显示一个图标。我有一些问题,windows缩放图标,使它非常难看。我能够通过使用图标 Package 器类解决这个问题,如这里所述。
使用 Package 器类解决了我遇到的缩放问题,但也带来了一个新问题:当我将鼠标移到按钮上时,图标只显示一次,如下所示:
下面是一个简单的例子:
import javax.swing.*;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
public class Ui {
private static JFrame frame;
private static JButton button1;
private static JButton button2;
private static JMenuBar jMenuBar;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
createGui();
} catch (MalformedURLException e) {
e.printStackTrace();
}
});
}
private static void createGui() throws MalformedURLException {
frame = new JFrame("Test");
button1 = new JButton();
button2 = new JButton();
jMenuBar = new JMenuBar();
Icon icon = new NoScalingIcon(new ImageIcon(new URL("https://i.stack.imgur.com/wgKeq.png")));
button1.setIcon(icon);
button2.setIcon(icon);
jMenuBar.add(button1);
jMenuBar.add(button2);
frame.setJMenuBar(jMenuBar);
frame.pack();
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
图标 Package 类:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
public class NoScalingIcon implements Icon {
private Icon icon;
public NoScalingIcon(Icon icon) {
this.icon = icon;
}
public int getIconWidth() {
return icon.getIconWidth();
}
public int getIconHeight() {
return icon.getIconHeight();
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at = g2d.getTransform();
int scaleX = (int) (x * at.getScaleX());
int scaleY = (int) (y * at.getScaleY());
int offsetX = (int) (icon.getIconWidth() * (at.getScaleX() - 1) / 2);
int offsetY = (int) (icon.getIconHeight() * (at.getScaleY() - 1) / 2);
g2d.setTransform(new AffineTransform());
icon.paintIcon(c, g2d, scaleX + offsetX, scaleY + offsetY);
g2d.dispose();
}
}
这个问题的原因是什么?
1条答案
按热度按时间u5i3ibmn1#
我想我找到了解决办法。
而不是创造一个全新的
AffineTransform
,下面的代码将一个新的缩放变换与现有缩放的倒数合并,以便将缩放因子设置回1: