Reputation:
I am quite new to java from c# background. I am following this tutorial to add an image to my Project and display in a label. In c# we use Picture-box and set the image property, In c# i can also re-size the image in a picture-box at design time by resizing the picture-box.
I have followed the tutorial and added the image to a label but the problem now is that the image is quite big and i want to re-size. I have tried resizing the label but i the image doesn't compress or re-size.
What am i supposed to do to re-size the image?
EDIT :
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/me/musiconweb/resources/Music-icon.png"))); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(40, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
pack();
Upvotes: 0
Views: 4646
Reputation: 8532
Try the following:
Change
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/me/musiconweb/resources/Music-icon.png")));
TO
BufferedImage img = null;
try {
img = ImageIO.read(new File("/org/me/musiconweb/resources/Music-icon.png"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage dimg = img.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
jLabel1.setIcon(new javax.swing.ImageIcon(dimg));
Hope that works. :)
Also, please take into consideration what @MadProgrammer discussed about not using getScaledImage. Though, if I were in your shoes, I would do incremental phases, first trying this out and if this works, go ahead and use the Graphic.scaleImage method.
For more info follow Resize a picture to fit a JLabel
Upvotes: 1