当您将图标连接到 JButton 时 (按钮.setIcon(图标);) 你得到的图标非常小,我怎样才能改变这个图标的大小?
我的代码: (在此代码中,您需要将 1 个文件拖到框架中,看看图标有多小)
JFrame frame = new JFrame();
JPanel p = new JPanel();
p.setTransferHandler(new TransferHandler(){
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
for (DataFlavor flavor : support.getDataFlavors()) {
if (flavor.isFlavorJavaFileListType()) {
return true;
}
}
return false;
}
@Override
@SuppressWarnings("unchecked")
public boolean importData(TransferHandler.TransferSupport support) {
if (!this.canImport(support))
return false;
java.util.List<File> files;
try {
files = (List<File>) support.getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
return false;
}
for (File file: files) {
String name = file.getName();
JPanel panel = new JPanel();
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
JButton button = new JButton(name);
button.setIcon(icon);
panel.add(button);
p.add(panel);
SwingUtilities.updateComponentTreeUI(frame);
}
return true;
}
});
frame.add(p);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
在我的期望中,我想要更改图标大小的选项(我需要按钮上的图标)
我尝试获取文件的img(没有成功):
Image img = ImageIO.read(file.getAbsolutePath());
这是一个简单的程序,它允许您使用滚轮控制图标的大小。
import java.awt.Image;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileSystemView;
public class Main {
File file = new File("path-to-your-file.png");
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
int size = 100;
public Main() {
JFrame jf = new JFrame();
JLabel jl = new JLabel();
jl.setIcon(icon);
jf.addMouseWheelListener(e -> {
size -= e.getWheelRotation();
Image image = ((ImageIcon) icon).getImage().getScaledInstance(size, size, Image.SCALE_FAST);
jl.setIcon(new ImageIcon(image));
});
jf.add(jl);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(500, 500);
jf.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Main());
}
}
第 1 步: 将默认图标保存在新变量中。我们将使用
icon
作为示例。ImageIcon
转换添加到您的 icon
,如上面的程序所示。确保括号内有 (ImageIcon) icon
,否则最终输出将转换为 ImageIconImage#getScaledInstance
缩放从 ImageIcon 获得的图像。我希望这有帮助:)