Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中构建可视化组件时防止焦点_Java_Focus_Javax.imageio_Jcomponent - Fatal编程技术网

在Java中构建可视化组件时防止焦点

在Java中构建可视化组件时防止焦点,java,focus,javax.imageio,jcomponent,Java,Focus,Javax.imageio,Jcomponent,我创建了一个应用程序,它需要在整个程序执行过程中多次重新加载图像。也许这很笨拙,但我的实现是在子类中扩展组件类,并通过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.IOE

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

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

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

即使您确实需要一个定制组件,但不会扩展该组件,您也会在Swing应用程序中扩展JComponent或JPanel

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

frame.setWindowFocusableState( false );

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

感谢您提供两条有用的信息。1.setVisible(true)窃取焦点,2。JFrame更好。