Como redimensionar imagem em uma jlabel?

Java

12/04/2015

Como redimensionar imagem em uma jlabel?
Reinilton

Reinilton

Curtidas 0

Respostas

Ronaldo Lanhellas

Ronaldo Lanhellas

12/04/2015

Você deve converter a imagem para BufferedImage e depois fazer o redimensionamento, independente se é jlabel ou não:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

BufferedImage dimg = img.getScaledInstance(label.width, label.height,
        Image.SCALE_SMOOTH);
GOSTEI 0
Ronaldo Lanhellas

Ronaldo Lanhellas

12/04/2015

Você deve converter a imagem para BufferedImage e depois fazer o redimensionamento, independente se é jlabel ou não:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

BufferedImage dimg = img.getScaledInstance(label.width, label.height,
        Image.SCALE_SMOOTH);
GOSTEI 0
Reinilton

Reinilton

12/04/2015

Não consegui usar o código acima, sou iniciante na linguagem.
Alguém pode passar o código completo?
GOSTEI 0
Ronaldo Lanhellas

Ronaldo Lanhellas

12/04/2015

Poste o seu JLabel, e como você está colocando a imagem nele. A partir disso você poderá usar o código acima postado.
GOSTEI 0
Reinilton

Reinilton

12/04/2015

Fiz isso aqui mas não consegui colocar o trecho que você colocou!


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;

public class AlbumDeFotos extends JFrame{

JLabel jlabel;
JButton botao;
ImageIcon imageIcon;
Image imagem;
Dimension dimensao;

public AlbumDeFotos() {
super("Minha Janela");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
setVisible(true);
}

public void distribui(){

jlabel = new JLabel();
jlabel.setBounds(10, 10, 100, 100);
jlabel.setBackground(Color.red);
jlabel.setBorder(LineBorder.createBlackLineBorder());
jlabel.setVisible(true);
add(jlabel);
imageIcon = new ImageIcon(getClass().getResource("imagens//imagem1.jpg"));
jlabel.setIcon(imageIcon);

}

public static void main(String[] args) {
new AlbumDeFotos().distribui();
}

}
GOSTEI 0
Ronaldo Lanhellas

Ronaldo Lanhellas

12/04/2015

Tente assim:


BufferedImage img = ImageIO.read("imagens//imagem1.jpg");
BufferedImage dimg = img.getScaledInstance(label.width, label.height,
        Image.SCALE_SMOOTH);
IconImage imageIcon = new IconImage(dimg);
GOSTEI 0
Ronaldo Lanhellas

Ronaldo Lanhellas

12/04/2015

Tente assim:


BufferedImage img = ImageIO.read("imagens//imagem1.jpg");
BufferedImage dimg = img.getScaledInstance(label.width, label.height,
        Image.SCALE_SMOOTH);
IconImage imageIcon = new IconImage(dimg);
GOSTEI 0
POSTAR