gpt4 book ai didi

java - 如何更新存储图像的 JLabel

转载 作者:行者123 更新时间:2023-12-01 09:24:59 25 4
gpt4 key购买 nike

我正在尝试通过 JButton 下载某些图片。

表单启动,有一个 JTextBox,我在其中写入 ID,因此按钮应该获取照片,但我真的不知道如何更新用于存储和显示图像的 JLabel。

我设置了默认 URL,因此启动时会始终显示相同的图片。

使用 JLabel 是存储和显示图像的最佳方式?

可以调整照片大小吗?

谢谢

<小时/>
package fotoMatricula;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FotoMatricula {

private JFrame frame;
private JTextField textField;
private String foto;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FotoMatricula window = new FotoMatricula();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public FotoMatricula() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
public void initialize() {
Image image = null;
try {
URL url = new URL("https://charal.unacar.mx/fotos/103522.jpg");
image = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}

frame = new JFrame();
frame.setBounds(100, 100, 391, 396);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JLabel lblIntroduceTuMatrcula = new JLabel("Introduce tu matr\u00EDcula");
lblIntroduceTuMatrcula.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblIntroduceTuMatrcula.setBounds(104, 11, 174, 24);
frame.getContentPane().add(lblIntroduceTuMatrcula);

textField = new JTextField();
textField.setBounds(139, 46, 94, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);

JLabel lblNewLabel = new JLabel(new ImageIcon(image));
lblNewLabel.setBounds(89, 77, 202, 189);
frame.getContentPane().add(lblNewLabel);


JButton btnBuscar = new JButton("Buscar");
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
foto = textField.getText();
lblNewLabel.setText(foto);
}
});
btnBuscar.setBounds(139, 303, 89, 23);
frame.getContentPane().add(btnBuscar);
}
}

最佳答案

这样做,就像你在初始化时所做的那样......在你的actionListener中试试这个:

 try
{
URL url2 = new URL (textField.getText());
lblNewLabel.setIcon(new ImageIcon(ImageIO.read(url2)));
}
catch (Exception e)
{

}

关于java - 如何更新存储图像的 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39909279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com