1

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

4

1 回答 1

2

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

不需要自定义组件。当您想要更改图像时,只需使用 JLabel 和 setIcon(...) 方法。

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

自动设置可见的框架会赋予框架焦点。您可以尝试使用:

frame.setWindowFocusableState( false );

然后您可能需要将 WindowListener 添加到框架中。当窗口打开时,您可以将可聚焦状态重置为 true。

于 2011-05-12T04:50:12.220 回答