在 Java 中构建视觉组件时阻止焦点



我创建了一个应用程序,该应用程序需要在整个程序执行过程中多次重新加载图像。也许这很笨拙,但我的实现是在子类中扩展 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),但它仍然设法窃取焦点。我如何告诉它是可聚焦的,但不是自动聚焦施工?

也许这很笨拙,但我的实现是在子类中扩展 Component 类,并通过 fileName 参数将图像重新加载到它的构造函数中

不需要自定义组件。只需使用 JLabel 和 setIcon(...) 方法即可更改图像。

即使你确实需要一个自定义组件,你也不会扩展组件,你会在 Swing 应用程序中扩展 JComponent 或 JPanel。

设置帧可见会自动提供帧焦点。您可以尝试使用:

frame.setWindowFocusableState( false );

然后,您可能需要向框架中添加窗口侦听器。打开窗口后,您可以将可聚焦状态重置为 true。

最新更新