How to edit changable icon scale? - java

As I know, to scale icon is toward button itself .
Like this
final JButton satu = new JButton((new ImageIcon(((new ImageIcon("images/1.png").getImage().getScaledInstance(50,50,java.awt.Image.SCALE_SMOOTH))))));
But when I modify to be changeable icon
I don't know how to scale it
is somebody know how to fix it ?
This is the code
final ImageIcon iconsatu = new ImageIcon("images/1.png");
final ImageIcon iconSatu = new ImageIcon("images/r1.png");
satu.addActionListener(new ActionListener() {
private boolean flag = true;
public void actionPerformed(ActionEvent e) {
satu.setIcon(flag?iconsatu:iconSatu);
flag=!flag;
}
});

I don't understand the question. You know how to scale an image as you demonstrated in your first line of code.
So why can't you simply create two scaled Icons:
Icon icon1 = new ImageIcon(((new ImageIcon("images/1.png").getImage().getScaledInstance(...))));
Icon icon2 = new ImageIcon(((new ImageIcon("images/2.png").getImage().getScaledInstance(...))));
Although that code is too complicated. You can simplify it by using something like:
BufferedImage image1 = ImageIO.read( new File("images/1.png") );
Icon icon1 = new ImageIcon( image1.getScaledInstance(...) );

Related

Setting ImageIcon to full screen

I have made a Board class, where I import an image using ImageIcon and, instead of making a picture with the specified resolution, I want it to be full screen for any type of monitor.
public Board() {
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon("C:/test.jpg");
img = i.getImage();
time = new Timer(5, this);
time.start();
}
I've used this code before:
public class MainMenu2 {
MainMenu2() throws IOException{
JFrame Main_Menu = new JFrame("Main Menu");
Main_Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final int widthScreen = screenSize.width;
final int heightScreen = screenSize.height;
BufferedImage backgroundImage = ImageIO.read(new File("P://My Pictures//background1.jpg"));
JLabel background = new JLabel(new ImageIcon(backgroundImage));
Image scaleBackground = backgroundImage.getScaledInstance(widthScreen, heightScreen, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(scaleBackground);
Main_Menu.setContentPane(new JLabel(imageIcon));
which uses scale smooth, which sets the image to the screen width and height, but I don't know how to apply it to my current code. The difference between both is that, Board class extends JPanel, and MainMenu2 is just a normal class, where a JFrame is created, etc. Please help! Thank you.
At the most basic level, it might look some like this...
ImageIcon i = ImageIO.read(new File("C:/test.jpg"));
Image scaleBackground = backgroundImage.getScaledInstance(widthScreen, heightScreen, Image.SCALE_SMOOTH);
img = scaleBackground.getImage();
Now, problems - the size of the component isn't likely to match he size of the screen.
As a preference, I might be tempted to do something like Scale the ImageIcon automatically to label size
You should also read The Perils of Image.getScaledInstance()

Images doesn't work in eclipse

I already did search on youtube and here and probably it is silly question but I couldn't find how to make it work.
Question is when I add pictures in my eclipse file they look like;
setLayout(new FlowLayout());
image1 = new ImageIcon(getClass().getResource("view.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("view1.jpg"));
label1 = new JLabel(image2);
add(label2); // here my code
Any ideas?
My got a use method to set icon for label, you can refer
private void loadAvartar(JLabel lbl, String path){
try {
BufferedImage image = ImageIO.read(new File(path));
ImageIcon icon = new ImageIcon(image.getScaledInstance(100, 100, 50));
lbl.setIcon(icon);
} catch (IOException | java.lang.NullPointerException e) {
lbl.setText("Failed");
}
}

Images not visible in JList

I'm writing a little photo application (asked some questions before) and I have one problem which I cannot resolve. The idea is that there are two sections: the upper one is for an overview (using thumbnails) and the lower one shows the selected image in it's full size. I cannot use ImageIO (required by my lecturer).
I'm using a JList for the overview but most images are not visible. I chose a folder with about 20 images and only 2 show up. And one of them isn't even centered.
For some reason, if I delete those lines:
thumbnaillist.setFixedCellWidth(thumbW);
thumbnaillist.setFixedCellHeight(thumbH);
One image shows up that wasn't visible before, but now the other two disappear.
This is my code:
public class PVE extends JFrame {
private JFileChooser fileChoose;
//MenuBar
private JMenuBar menubar;
private JMenu file;
private JMenuItem openFolder;
private JMenuItem exit;
//Thumbnails
private JList thumbnaillist;
private DefaultListModel<ImageIcon> listmodel;
private JScrollPane tscroll;
private ImageIcon thumbs;
private int thumbW = 100;
private int thumbH = 100;
//for full size view
private JPanel imgview;
public PVE() {
setLayout(new BorderLayout());
//MenuBar
menubar = new JMenuBar();
file = new JMenu("File");
openFolder = new JMenuItem("Open folder...");
exit = new JMenuItem("Quit");
file.add(openFolder);
file.addSeparator();
file.add(exit);
menubar.add(file);
setJMenuBar(menubar);
fileChoose = new JFileChooser();
openFolder.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
fileChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChoose.showOpenDialog(null);
File chosenDir = fileChoose.getSelectedFile();
loadToThumbView(chosenDir);
}
});
//Thumbnail view
listmodel = new DefaultListModel();
thumbnaillist = new JList(listmodel);
thumbnaillist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
thumbnaillist.setFixedCellWidth(thumbW);
thumbnaillist.setFixedCellHeight(thumbH);
thumbnaillist.setVisibleRowCount(1);
tscroll = new JScrollPane(thumbnaillist, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tscroll.setPreferredSize(new Dimension(0, 100));
add(tscroll, "North");
//for full size view
imgview = new JPanel();
imgview.setBackground(Color.decode("#f7f7f7"));
add(imgview, "Center");
setTitle("Photo Viewer");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
}
setSize(700, 700);
setLocation(200, 200);
setVisible(true);
}
public void loadToThumbView(File folder) {
listmodel.removeAllElements();
File[] imgpaths = folder.listFiles();
for (int j = 0; j < imgpaths.length; j++) {
listmodel.addElement(resizeToThumbnail(new ImageIcon(imgpaths[j].toString())));
}
}
public ImageIcon resizeToThumbnail(ImageIcon icon) {
Image img = icon.getImage();
BufferedImage bf = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bf.createGraphics();
g.drawImage(img, 0, 0, thumbW, thumbH, null);
ImageIcon kB = new ImageIcon(bf);
return kB;
}
public static void main(String argv[]) {
PVE pv = new PVE();
}
}
Your problem is because of the way you're scaling your images.
I'm not exactly sure why but I guess it has something to do with the BufferedImage#createGraphics() call and that I was able to reproduce the problem with .jpg images while .png files were correctly painted.
However if you scale your images instead of converting them to a BufferedImage and getting a new ImageIcon from it, you get the correct output:
public ImageIcon resizeToThumbnail(ImageIcon icon) {
Image img = icon.getImage();
Image scaled = img.getScaledInstance(thumbW, thumbH, Image.SCALE_SMOOTH);
return new ImageIcon(scaled);
}
This is the folder I used to test:
And the outputs with your code and mine:
Important notes
And as as a recommendation don't make a window that big if all you're using is that little bar above. If you're adding something else below, then it's ok but for now it's not that "user friendly" (IMHO). Instead of JFrame#setSize() you could try using JFrame#pack() method so your frame resizes to it's preferred size.
Some other things I noted in your program:
You're not placing it inside the Event Dispatch Thread (EDT) which is dangerous since your application won't be Thread safe that way. You can change that if you change your main method as follows:
public static void main(String argS[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PVE pv = new PVE();
}
});
}
You're setting the JScrollPane preferred size, instead you should override its getPreferredSize() method, see Should I avoid the use of setPreferred|Maximum|MinimumSize methods in Java Swing? (YES)
You're extending JFrame, you should instead create an instance of it unless you're overriding one of its methods (and you're not, so don't do it) or you have any good reason to do it. If you need to extend a Container you should extend JPanel instead, as JFrame is a rigid container which cannot be placed inside another one. See this question and this one.
I think I'm not missing anything, and hope this helps
Your “scaled” images are actually images which are the same size as the original image, but are blank except for a scaled version drawn in the upper left corner. That upper left corner is clipped out of view in each rendered cell (at least for the somewhat large images I tested with).
The scaled image needs to be created with the thumbnail size, not the size of the original image. Meaning, change this:
BufferedImage bf = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
to this:
BufferedImage bf = new BufferedImage(thumbW, thumbH, BufferedImage.TYPE_INT_ARGB);

Picture Format with frame.pack()

With this code, I visualize a picture after performing a search . The user has the possibility to change that image selected by clicking a button and then opening a picture editor (this is not the main point at the moment) , I would put a button in the right side of the image. Now with the pack () , the window size is the same as the picture, how do I insert a button ( with its image) keeping fixed the other three sides or at least having the same distance from right and left ?
public static void VisImmagine(JFrame frame, String Indirizzo)
{
Image image = null;
try {
URL url = new URL(Indirizzo);
image = ImageIO.read(url);
} catch (IOException e) {
}
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.AFTER_LAST_LINE);
// frame.setSize(10, 10);
frame.pack();
////UPDATE
int larghezza = frame.getWidth();
int altezza = frame.getHeight();
frame.setSize(larghezza+250, altezza)
//////
frame.setVisible(true);
}
Hope I was clear enough, thanks in advance to everybody.

How to load an image to a JButton in java?

I want to load an image to a JButton in a java application so when I click the button to show the image and when I click it again to hide the image.I don't want the image to be loaded to a label but on the button.
I'm thinking in SWT, but I guess this works for Swing too.
final JButton button = new JButton();
final ImageIcon icon = new ImageIcon(image);
button.setIcon(icon);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setIcon( button.getIcon() == null ? icon : null );
}
});
You can try this:
ImageIcon iconStart = new ImageIcon("start.jpg");
JButton bttnStart = new JButton(iconStart);

Categories