我一直在学习 Oracle 教程中的图像:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class LoadImageApp extends Component {
BufferedImage img;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public LoadImageApp() {
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new LoadImageApp());
f.pack();
f.setVisible(true);
}
}
我想更改 JFrame 中显示的图像。如果我说:
f.add(new LoadImageApp());
f.revalidate();
f.repaint();
新图像将出现在当前图像的后面。我想做的是删除以前的图像并替换,但我不知道如何用这段代码来做到这一点?
为什么不直接使用 JLabel 来显示图像呢?然后要更改图像,您只需调用 setIcon(...) 方法。
如果您确实需要进行定制绘画,那么:
对于 Swing 应用程序,您应该扩展 JComponent,而不是 Component
你应该重写paintComponent(),而不是paint()
如果您想更改图像,请创建一个类似
setImage()
的方法来更改图像。然后在该方法中调用 repaint() 来强制组件重新绘制自身。无需创建新组件并替换 GUI 上的组件。您遇到的问题是您正在堆叠图像而不删除旧图像。 请执行以下操作: 原始代码中:
BufferedImage img = new LoadImageApp();
f.add(img);
f.pack();
f.setVisible(true);
当您想加载另一张图像时:
img = new LoadImageApp();
// No need to add the image to the frame again, just refresh
f.repaint();
这是我的贡献,主要用于测试。这个想法是改变图像改变的基础
JPanel
。这个类可以添加到另一个 JPanel
或 JFrame
中,并且您仍然可以更改图像。
public class ImageButton extends JPanel {
public JLabel imageLabel;
public ImageButton() {
super();
iniGUI();
}
private void iniGUI() {
JPanel panel = new JPanel();
imageLabel = new JLabel(" ");
panel.setLayout(new BorderLayout());
panel.add(imageLabel, BorderLayout.NORTH);
JButton clickButton = new JButton("Select...");
panel.add(clickButton, BorderLayout.SOUTH);
clickButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
imageLabel.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
panel.setPreferredSize(new Dimension(200, 200));
panel.setBorder(BorderFactory.createLineBorder(Color.black));
this.add(panel, BorderLayout.CENTER);
}
public static void main(String...arg){
JFrame cadre = new javax.swing.JFrame(" ");
cadre.setContentPane(new ImageButton());
cadre.setPreferredSize(new Dimension(600, 600));
cadre.setLocation(300, 300);
cadre.pack();
cadre.setVisible(true);
cadre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}