尝试导入自己的包

5
package mainClasses;
    /*
     * Frame Info and all that ****,
     * mainFrame is the actual frame itself
     * it will refer to MainC.java a lot Main class = Main Class
     */
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import JavaGame.src.resources.*; //Problem Code
    import javax.swing.JButton;
    import javax.swing.JFrame;


    public class mainFrame extends JFrame {


private static final long serialVersionUID = 1L;

public mainFrame() {
    JButton playButton = new JButton();
    JButton infoButton = new JButton();
    JButton exitButton = new JButton();
    int x = 300, y = 300;
    setSize(x, y);
    setVisible(true);
    setLayout(new FlowLayout());
    setTitle("Kingdom Raider");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    /*Buttons and Properties*/

     playButton.setBounds(x, y, 200, 100);
     playButton.setText("Play!");
    add(playButton);

     infoButton.setBounds(x, y, 200, 100);
     infoButton.setText("Information");
    add(infoButton);

     exitButton.setBounds(x, y, 200, 100);
     exitButton.setText("Exit");
    add(exitButton);
            /* Add image here */

}

public void Painting (Graphics g) {
    //Me.
}
   }

我正在创建一款游戏,遇到了导入问题。 如您所见,我想要导入JavaGame.src.resources,因为我正在尝试导入一张图片。 这是我的目录结构:

enter image description here

我不需要知道resourcesmanager.java文件的代码,目前是空白的。所以,基本上这个类在mainClasses包中,但我想访问resources包。怎么办?


包名只是 resourcessrc 文件夹和 JavaGame 文件夹不包括在内。 - Hunter McMillen
6个回答

5
您的包名是resources,因此请写成这样:
import resources.*; // No-Problem Code

目录结构的其余部分是特定于Eclipse的,与Java类路径无关。


嗯,那很奇怪。你能发更多信息吗?从你的截图来看应该足够了... - Lukas Eder

1

公平的观点,但在类路径上拥有资源并没有什么问题。 - maksimov

1

Eclipse会自动为您导入内容,如果您复制和粘贴某些东西-也许您可以编写一个使用JavaGame.src.resources中的内容的短剪辑,然后复制粘贴-eclipse将完成其余部分。


1

你的源文件夹是src,所以这是你的类层次结构的根目录。你应该做的是

import resources.*

然而,使用*是不好的形式,你应该尝试只导入这个特定类中需要的类,就像你在javax.swing.JButton中所做的那样。所以:

import resources.ResourceManager;

0
你想要做的是访问存储在资源文件夹中的文件。为了做到这一点,你不需要像你尝试过的那样导入文件夹。相反,按照Tony the Pony的建议使用以下方法:
getResource("FileName.ext")

作为一个例子,如果要将文件转换为图标,您需要使用资源路径:
java.net.URL path = this.getClass().getResource("FileName.jpg");
ImageIcon icon = new ImageIcon(path);

我还应该指出,如果您正在使用NetBeans,则需要将资源文件夹添加为源文件夹;否则,项目将无法按照您的要求进行编译,导致.jar文件无法访问资源文件。Eclipse可能类似。要将文件夹添加为源:

  1. 右键单击项目
  2. 选择属性
  3. 在类别窗格中单击“源”
  4. 单击“添加文件夹”,然后选择您创建的资源文件夹

0
我认为这可能是Eclipse配置的问题。有时Eclipse会将项目中的源文件夹视为包的一部分。只需从Eclipse工作区中删除项目而不从文件系统中删除它,然后再次导入即可解决问题。
这应该会有所帮助。
从Eclipse中删除项目而不从文件系统中删除它:

http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-42b.htm

将现有项目导入Eclipse:

http://agile.csc.ncsu.edu/SEMaterials/tutorials/import_export/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接