我尝试加载图像,我找到了一个代码,它运行良好,加载图像的代码在构造函数中,我试图将它移动到按钮操作,也移动到filechooser。但永远不要加载图像。代码中没有错误,我使用 print 语句测试了子句,它们表明子句通过了。
这是一个SSCCE:
构造函数代码分为上下两部分。通过注释和取消注释每个.
下部将起作用;它从构造函数加载图像。
上半部分设置了从 Action 代码加载图像所需的 JPanel 和 JButton。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ImgLoadTest extends JPanel implements ActionListener
{
File file;
BufferedImage img;
JButton fileChooserButton;
JButton showImgButton;
JPanel imgePanel;
JPanel widgetPanel;
JFileChooser fileChooser;
@Override
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 60, null);
}
public ImgLoadTest()
{
//Upper:
// fileChooser = new JFileChooser();
//
// fileChooserButton = new JButton("Browse");
// fileChooserButton.addActionListener(this);
// showImgButton = new JButton("Show Image");
// showImgButton.addActionListener(this);
//
// imgePanel = new JPanel();
// widgetPanel = new JPanel();
// this.setLayout(new BorderLayout());
// widgetPanel.add(fileChooserButton);
// widgetPanel.add(showImgButton);
// this.add(imgePanel, BorderLayout.CENTER);
// this.add(widgetPanel, BorderLayout.EAST);
/*
* try alternating (comment/uncomment) between
* the upper code (in this constructor)
* and the lower code below;
*/
//Lower:
try
{
img = ImageIO.read(new File("D:\\De.JPG"));
} catch (IOException e)
{
}
}
@Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == fileChooserButton)
{
int reternedValue = fileChooser.showOpenDialog(ImgLoadTest.this);
if (reternedValue == JFileChooser.APPROVE_OPTION)
{
file = fileChooser.getSelectedFile();
try
{
img = ImageIO.read(file);
System.out.println("File chooser: Image accepted");
this.repaint();
} catch (IOException err)
{
System.out.println("error " + err);
}
} else
{
System.out.println("No Image");
}
}
if (source == showImgButton)
{
try
{
System.out.println("button: Image accepted");
img = ImageIO.read(new File("D:\\De.JPG"));
repaint();
} catch (IOException err)
{
System.out.println("No Image");
System.out.println("error " + err);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Image load test");
frame.setSize(new Dimension(400, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImgLoadTest imgLoadTest = new ImgLoadTest();
frame.add(imgLoadTest);
frame.setVisible(true);
}
}