在Java中可视化组件构造期间防止焦点

时间:2011-05-12 04:16:04

标签: java focus javax.imageio jcomponent

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

1 个答案:

答案 0 :(得分:2)

  

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

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

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

自动设置框架可以显示框架焦点。您可以尝试使用:

frame.setWindowFocusableState( false );

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