简体   繁体   English

为什么没有显示背景图像?

[英]Why isn't the background image showing up?

I'm writing a program for a Hangman game and I want the background to be a JPEG image, rather than just a solid color. 我正在编写一个适用于Hangman游戏的程序,我希望背景是JPEG图像,而不仅仅是纯色。 But when I run my program, the background image isn't showing up. 但是,当我运行程序时,没有显示背景图像。 Any thoughts? 有什么想法吗?

HangmanFigure.java HangmanFigure.java

import java.awt.*;
import javax.swing.*;

    public class HangmanFigure extends JPanel {
       private int guesses;
       private Image background;

          public HangmanFigure() {
             super();
             guesses = 0;
             setPreferredSize(new Dimension(300, 300));

             //setting background color
             //setBackground(Color.BLACK);

             //setting background image to JPEG
             background = Toolkit.getDefaultToolkit().createImage("/Desktop/scaryTown.jpg");

             //set to true because we want to see the background
             setOpaque(true);
          }

          @Override
          public void paintComponent(Graphics g) {
             super.paintComponent(g);

             g.drawImage(background, 0, 0, null);
             //No need to worry about the rest of the elements in this method, I'm just having issues with the background image!
             ...
          }
       }

In another file, called MainWindow.java, I have the main method. 在另一个名为MainWindow.java的文件中,我有main方法。 (That's where I provide the graphics for everything else that's not part of the Hangman figure). (在这里,我为不属于Hangman人物的其他所有事物提供了图形)。 Thank you in advance! 先感谢您!

  • try to add the resource folder which contains your background photo to the build path by right click the folder in eclipse then build-path --> use as source folder , and you juste have to put "/YoursourceFolderName/scaryTown.jpg" 尝试通过右键单击eclipse中的文件夹,然后将build-path->用作源文件夹,将包含您的背景照片的资源文件夹添加到构建路径,然后只需放置“ /YoursourceFolderName/scaryTown.jpg”

if you are using command line to compile use the following command : 如果您使用命令行进行编译,请使用以下命令:

javac -d bin -sourcepath YourSourceFolder pathToTheJavaCode/*.java 

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

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