1
我創建了一個應用程序,要求在整個程序執行過程中多次重新加載一個圖像。也許這很笨拙,但我的實現是在子類中擴展Component類,並通過fileName參數將圖像重新加載到其構造函數中。該代碼包含如下:在Java中的可視化組件構建過程中防止焦點
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class Grapher {
private static JFrame frame = new JFrame("Test Frame");
private static Graph graph = null;
private static JScrollPane jsp = null;
public Grapher(){
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public void display(String fileName) {
if(jsp != null)
frame.getContentPane().remove(jsp);
graph = new Graph(fileName);
jsp = new JScrollPane(graph);
frame.getContentPane().add(jsp);
frame.setSize(graph.getPreferredSize());
frame.setVisible(true);
}
private class Graph extends Component{
BufferedImage img;
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public Graph(String fileName) {
setFocusable(false);
try {
img = ImageIO.read(new File(fileName));
} catch (IOException e) {System.err.println("Error reading " + fileName);e.printStackTrace();}
}
}
}
不管怎麼說,我的問題是,每當我稱之爲display
命令窗口搶斷一切的Java,包括Eclipse的焦點,它可以真正agravating。我甚至嘗試在構造函數中加入setFocusable(false)
,但它仍然設法竊取焦點。我如何告訴它是可以聚焦的,但不能自動集中施工?
感謝您提供兩條有用的信息。 1. setVisible(true)竊取焦點,2. JFrame更好。 – 2011-05-12 22:40:08