我有一个创建GUI的任务,当选择菜单项时(例如文件,新图片)切换图像,并且还包含用于放大和缩小图像的按钮。当我尝试使用我的代码切换图像时,图像仅部分加载。当我最小化窗口然后重新打开它时,图像被完全加载。我想知道为什么会这样。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class ImageZoom extends JPanel {
private Image image;
int x, y;
private JButton zoomIn;
private JButton zoomOut;
private JMenuBar bar;
private JMenu file;
private JMenuItem choosePic = new JMenuItem("New Picture");
private String pics[] = {"waterfall.jpg", "mountains.jpg"};
private int picIndex = 1;
int imageHeight = getHeight();
int imageWidth = getWidth();
int zoom = 1;
Image images[] = new Image[2];
public ImageZoom() {
try {
images[0] = ImageIO.read(new File("waterfall.jpg"));
images[1] = ImageIO.read(new File("mountains.jpg"));
} catch (IOException e) {}
zoomIn = new JButton("+");
zoomOut = new JButton("-");
JPanel panel = new JPanel();
bar = new JMenuBar();
file = new JMenu("File");
file.add(choosePic);
bar.add(file);
choosePic.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == choosePic) {
repaint();
}
}
});
zoomIn.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == zoomIn) {
if (zoom < 6) {
zoom += 1;
repaint();
}
}
}
});
zoomOut.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == zoomOut) {
if (zoom > 1) {
zoom -= 1;
repaint();
}
}
}
});
}
public JPanel getButtonPanel () {
JPanel panel = new JPanel();
panel.add(zoomIn);
panel.add(zoomOut);
return panel;
}
public Image getImage() {
try {
image = ImageIO.read(new File(pics[picIndex % 2]));
picIndex++;
}
catch (IOException e){}
return image;
}
protected void paintComponent (Graphics g) {
imageHeight = getHeight() * zoom;
imageWidth = getWidth() * zoom;
super.paintComponent(g);
g.drawImage(getImage(), 0, 0, imageWidth, imageHeight, null);
}
public void createJFrame () {
JFrame frame = new JFrame();
ImageZoom imgZoom = new ImageZoom();
frame.setJMenuBar(bar);
frame.add(imgZoom);
frame.add(getButtonPanel(), BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 650);
frame.setResizable(false);
frame.setVisible(true);
}
}
class Test {
public static void main (String[] args) {
ImageZoom zoom = new ImageZoom();
zoom.createJFrame();
}
}
答案 0 :(得分:1)
为简单起见,您应该使用JLabel
并调用其setIcon
方法来切换图像。您可以根据需要动态缩放图像(只保留对原始图像的引用)
您应该将this
传递给drawImage
,这将允许该组件充当ImageObserver
,并根据图像状态中的事件根据需要安排其他重印,从而导致
您不应该在getImage
方法中调用paintComponent
,paintComponent
可能会因为多种原因而被调用,其中许多原因是您无法控制甚至不知道的paintComponent
应该只绘制组件的当前状态,永远不要尝试更改状态
旁注:不要反复尝试加载图片,最好加载一次并继续重复使用已加载的参考