When you connect icon to JButton ( button.setIcon(icon); ) you get very small icon, How can I change the size of this icon?
My code: (In this code you need to drag 1 file to the frame and look how small the icon)
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);
In my expectation i want the option to change the size of the icon (I need the icon on the button)
I tried to get the img of the file (didn't work):
Image img = ImageIO.read(file.getAbsolutePath());
Here's a simple program which allows you to control the size of the icon using your scroll wheel.
Here's how you can achieve this in your program
Step 1: Save the default icon in a new variable. We'll use
iconas an example.Step 2: When you want to resize the image, add an
ImageIconcast to youriconas shown in the program above. Make sure you have(ImageIcon) iconwithin brackets, else this will cast the final output to ImageIconStep 3: Use
Image#getScaledInstanceto scale the image you get from the ImageIcon.Step 4: Finally change the JLabel icon to a new ImageIcon, with the image you had gotten from the previous step.
I hope this helps :)