【发布时间】:2015-04-22 20:10:37
【问题描述】:
在我的 java 程序中,我正在制作一个 GUI,它应该在单击 JButton 时在 JPanel 中显示捕获的图像。
下面是我创建的用于渲染捕获的图像的自定义 ImagePanel 类。
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public ImagePanel() {
try {
File f = new File("capture.jpg");
f.exists(); //this is returning false here, don't no why ?
image = ImageIO.read(f);
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
}
点击 JButton,在 ActionListener 中,我正在执行以下操作
@Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
System.out.println(s);
if (s.equals("Capture Image")) {
//Here calling a script to capture the image.
try {
Process proc = Runtime.getRuntime().exec("./capture.sh");
Thread.sleep(2000);
} catch (Exception e1) {
e1.printStackTrace();
}
ImagePanel panel = new ImagePanel();
containerPanel.add(panel);
containerPanel.revalidate();
containerPanel.repaint();
.....
不过,我的程序仍然无法检测到捕获的图像并显示它。但是当我下次单击 JButton 时,它会显示以前捕获的图像。
即使经过大量的努力,也无法发现问题。任何帮助表示赞赏。 谢谢!
【问题讨论】:
-
你确定你能进去吗?那个字符串比较看起来很糟糕。为什么你不使用 java 8 和 lambda button.addActionListener((e) -> { // your code}) ?
-
@Lukino 他的字符串比较没有问题。事实上,我想说使用
.equals()比一般的 lambda 好得多——如果一个不使用 Java 8 并且对 lambdas 一无所知的开发人员看到它怎么办?他会完全糊涂的。 -
@Aify - 然后我建议进入。这就像如果还有蜡烛,为什么要用电来照明房间?当您需要重构时,基于字符串常量的行为并不漂亮。至少把它放到 Enum 中,所以常量在 1 位。
-
那么你在哪里实际创建图像???发布一个正确的SSCCE 来证明问题。人们试图只用一半的信息来回答。您的 ActionListener 假定图像已经创建。
-
在论坛发帖完全不需要 lambda 表达式。您希望尽可能多的人能够阅读/执行您的代码。
标签: java swing events jpanel actionlistener