我创建了一个应用程序,需要在程序执行过程中多次重新加载图像。也许它很笨拙,但我的实现是在子类中扩展 Component 类,并通过其构造函数的 fileName 参数重新加载图像。代码如下:
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,这真的很烦人。我什至尝试在构造函数中添加 setFocusable(false) ,但它仍然设法窃取焦点。我如何让它可聚焦但在构造时不自动聚焦?
最佳答案
Perhaps it's clumsy, but my implementation was to extend the Component class in a subclass and reload the image via a fileName argument to it's constructor
不需要自定义组件。当您想要更改图像时,只需使用 JLabel 和 setIcon(...) 方法即可。
即使您确实需要自定义组件,您也不会扩展 Component,而是会在 Swing 应用程序中扩展 JComponent 或 JPanel。
将框架设置为可见会自动赋予框架焦点。您可以尝试使用:
frame.setWindowFocusableState( false );
然后您可能需要向框架添加一个 WindowListener。当窗口打开时,您可以将可聚焦状态重置为 true。
关于java - 在 Java 中构建可视化组件期间防止焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5973236/