【问题标题】:Code isn't working, trying to get image to show [closed]代码不起作用,试图让图像显示[关闭]
【发布时间】:2013-12-31 21:51:58
【问题描述】:

我真的不明白为什么我的代码不能显示这张牛的图片,有什么建议吗?我根据我的信息正确地做了一切。所以我不太确定出了什么问题。我使用eclipse,程序没有显示错误。因此,如果有人可以提供帮助,将不胜感激。提前致谢。

    package Zeus;

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;


public class Main extends JFrame{

    public static final int WIDTH = 400;
    public static final int HEIGHT = 300;
    public static final int SCALE = 2;

    private ImageIcon COW;
    private static JLabel C0W;

    Main() {
        setLayout(new FlowLayout());

        COW = new ImageIcon(getClass().getResource("/Cow Clicker/Resource/COW.png"));
        C0W = new JLabel(COW);

    }

    public static void main(String[] args) {

        JFrame Squishy = new JFrame("Squishy");
        Squishy.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Squishy.setResizable(false);
        Squishy.setVisible(true);
        Squishy.setSize(WIDTH*SCALE, HEIGHT*SCALE);
        Squishy.setLocationRelativeTo(null);

        Squishy.add(C0W);
    }

}

【问题讨论】:

    标签: java image swing embedded-resource


    【解决方案1】:

    您需要创建Main 的实例,以便可以从其构造函数加载图像。

    【讨论】:

    • 1+。那是疯狂的代码。
    • 肯定是,会弄出一些替代代码,已经由 nachokk、nvm...
    • 很难从哪里开始,但你明白了:D +1
    【解决方案2】:

    我不知道从哪里开始

    1st) 按照惯例,java 中的变量以骆驼样式后的小写字母开头。 所以你的变量COW应该改为cow等等。

    2nd)恕我直言,我从不使用像 C0W 这样的变量名称。

    3rd) 你正在扩展JFrame 没有任何理由,所以把你的代码改成这个。

    public class Main{
    
        public static final int WIDTH = 400;
        public static final int HEIGHT = 300;
        public static final int SCALE = 2;
        private JFrame frame;
        private ImageIcon cow;
        private JLabel labelCow; // remove static
    
        public Main() {
            frame = new JFrame();
            frame.setLayout(new FlowLayout());
    
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setSize(WIDTH*SCALE, HEIGHT*SCALE);
            frame.setLocationRelativeTo(null);
    
            cow = new ImageIcon(getClass().getResource("Cow Clicker/Resource/COW.png"));
            labelCow = new JLabel(cow);
            frame.add(cow);
            //pack(); you are using setSize
            setVisible(true);
        }
    
    
    
    
    
        public static void main(String[] args) {
                   SwingUtilities.invokeLater(new Runnable(){
                         @Override
                         public void run(){
                             new Main();
                         }
    
                    });
         }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-09
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多