使用windowlisteners时,图像会出现和消失

时间:2017-12-14 20:33:39

标签: java

当我使用窗口监听器来调用类时,生成的图像出现在我的画布上,然后不久就消失了。当我使用mouseclicklistener或actionperformedlistener等监听器时,我没有同样的问题。我想首次打开程序时自动显示图像。任何人都可以向我解释为什么会这样吗?

    private void nyttkart(){
    vindu = "&WIDTH=" + bredde + "&HEIGHT=" + høyde;
    bbox = "&BBOX=" + String.valueOf(vestl) + "," + String.valueOf(sørl)
            + "," + String.valueOf(østl) +"," + String.valueOf(nordl);
    try {
        URL kart = new URL("http://openwms.statkart.no/skwms1/wms.topo4?VERSION=1.3.0"
                + "&REQUEST=GetMap&CRS=EPSG%3A25832&FORMAT=image/png"
                + "&SERVICE=WMS&LAYERS=Hoydelag,Arealdekkeflate,"
                + "Vannflate,Vannkontur,Elver,Hoydekurver,Veger,Jernbane"
                + bbox + vindu);
        InputStream is = kart.openStream();
        Image image = ImageIO.read(is);
        canvas1.getGraphics().drawImage(image,0,0,null);
    } catch (MalformedURLException ex) {
        Logger.getLogger(SOSI_Utvalg.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SOSI_Utvalg.class.getName()).log(Level.SEVERE, null, ex);
    }
}

1 个答案:

答案 0 :(得分:0)

这不是绘画的作用方式。你不要告诉Canvas给你一个图形;相反,您覆盖一个paint方法,系统在需要您绘制时调用该方法。有关详细信息,请参阅https://docs.oracle.com/javase/tutorial/uiswing/painting/

那就是说,你不需要Canvas来显示图像:

 [(i,j) for i=1:3, j=1:i]
 ERROR: UndefVarError: i not defined

如果要在无法加载图像时接收IOExceptions,可以先加载图像,然后传递它:

Component imageComponent = new JLabel(new ImageIcon(kart));

作为旁注,在连接对象以形成String时,会隐式调用String.valueOf。您无需明确调用它:

Image image = ImageIO.read(kart);
Component imageComponent = new JLabel(new ImageIcon(image));