作爲一名java非專家,我想知道如何更改下面的代碼以使其工作。這是我想要做的如何顯示/更新JFrame中java中的按鍵後的圖像?
- Java代碼的時候被稱爲
args
包含多個圖像文件名 - 我想看到的第一個圖像在此列表中
- 然後當我按一個鍵,索引是改變,並顯示下一個圖像。
使用下面進行,這裏的建議是編譯,運行一段代碼:
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;
private static int index = 0;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public LoadImageApp(String filename) {
try {
img = ImageIO.read(new File(filename));
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
static public void changeImage(JFrame frame, String filename) {
System.out.println("Using file "+filename);
frame.add(new LoadImageApp(filename));
frame.pack();
frame.setVisible(true);
frame.repaint();
}
public static void main(final String[] args) {
char c=0;
String filename = args[0];
int numberImages = args.length;
final JFrame f = new JFrame("Load Image Sample");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
f.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
if (key==81) {
System.exit(0);
} else if (key==89) {
System.out.println("yes");
} else if (key==78) {
System.out.println("no");
}
index += 1;
f.removeAll();
changeImage(f, args[index]);
}
});
// show first image here
changeImage(f, args[index]);
}
}
如果我用用類似的代碼
java LoadImageApp *.jpg
它只顯示第一個圖像。我可以按鍵,但顯示的圖像不會改變。我想要改變圖像。我發現revalidate()
和repaint()
作爲可能的解決方案。儘管frame.revalidate()
完全不存在,但frame.repaint()
(在changeImage
之內)仍然沒有任何改變。我仍然看到顯示的第一個圖像。
無論如何這是正確的方法嗎?有沒有更優雅的方式?
如果你不喜歡'最終'變量不使用匿名類。爲'KeyAdapter'創建一個常規類。 – omainegra
我不知道最後的變量是什麼。或者如果在我的情況下如何使用它們,如果解決了我的問題。 – Alex
爲了儘快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –