简体   繁体   English

向JFrame添加图像

[英]Adding an image to the JFrame

I want to add an Image to the JFrame, the add( ) method is generating an error which says "cannot find symbol: method add(JLabel)" ... How can I fix that? 我想将图像添加到JFrame, add( )方法生成一个错误,提示“找不到符号:方法add(JLabel)” ...我该如何解决?

** I still haven't called the ImageLoading( ) method from the main method. **我还没有从main方法中调用ImageLoading( )方法。

import javax.swing.*;

public class NetworkingGame {

NetworkingGame(){
    JFrame jfrm = new JFrame("Angry Painters");
    jfrm.setSize(800, 480);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jfrm.setVisible(true);

}

public void ImageLoading(){
    ImageIcon i = new ImageIcon("angry-painters.jpg");
    JLabel jl = new JLabel(i);
    add(jl); //The error is in this line
}

public static void main(String[] args) throws Exception{
    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run(){
            new NetworkingGame();
        }
    });

   }
}

Visibility of JFrame jfrm is limited by constructor of NetworkingGame . JFrame jfrm可见性受NetworkingGame的构造函数限制。 So add method does not exist in NetworkingGame . 因此, NetworkingGame中不存在add方法。 Make your JFrame member of NetworkingGame . 使您的JFrame成为NetworkingGame成员。

public class NetworkingGame {
    private JFrame jfrm;

    NetworkingGame(){
        jfrm = new JFrame("Angry Painters");


    ...

        JLabel jl = new JLabel(i);
        jfrm.add(jl);

Probably you should write 也许你应该写

jfrm.add(jl); 

and have jfrm as a member. 并拥有jfrm作为成员。

In you case you really calling this.add() which is not exist. 在这种情况下,您实际上调用了不存在的this.add()

You are calling the add method as if it was an instance method in your class NetworkingGame and your class doesn't have any method, so you are getting the compiler error as the compiler can't find any method of such a name in your class NetworkingGame , so add it to the Jframe instead. 您正在调用add方法,就好像它是您的类NetworkingGame的实例方法,并且您的类没有任何方法,因此您会遇到编译器错误,因为编译器在您的类中找不到此类名称的任何方法NetworkingGame ,因此请将其添加到Jframe中。

NetworkingGame(){
    JFrame jfrm = new JFrame("Angry Painters");
    jfrm.setSize(800, 480);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jfrm.setVisible(true);
    ImageIcon i = new ImageIcon("angry-painters.jpg");
    JLabel jl = new JLabel(i);
    jfrm.add(jl);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM