最近突然来劲,准备学点Java,其中一个示例程序用到了目录中的图片文件,可程序运行时,却没将图片显示出来,部分代码如下:
- package ch09;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class ToolBarTest {
- // omitted here ......
- }
- class ToolBarFrame extends JFrame{
- public ToolBarFrame(){
- // omitted here ......
-
- Action blueAction = new ColorAction("Blue",new ImageIcon("blue-ball.gif"),Color.BLUE);
-
- Action yellowAction = new ColorAction("Yellow",new ImageIcon("yellow-ball.gif"),Color.YELLOW);
-
- Action redAction = new ColorAction("Red",new ImageIcon("red-ball.gif"),Color.RED);
-
- Action exitAction = new AbstractAction("Exit",new ImageIcon("exit.gif")){
-
- public void actionPerformed(ActionEvent event){
-
- System.exit(0);
-
- }
-
- };
-
- // omitted here ......
- }
- }
此时上述4个图片文件与程序源文件位于同一目录下,路径为:CoreJavaV1\src\ch09\*.*
最后发现程序中的路径是相对于工程目录而言的,也就是默认工作目录为:CoreJavaV1,通过修改上述程序如下,问题得到解决:
- package ch09;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class ToolBarTest {
- // omitted here ......
- }
- class ToolBarFrame extends JFrame{
- public ToolBarFrame(){
- // omitted here ......
-
- Action blueAction = new ColorAction("Blue",new ImageIcon("src/res/blue-ball.gif"),Color.BLUE);
-
- Action yellowAction = new ColorAction("Yellow",new ImageIcon("src/res/yellow-ball.gif"),Color.YELLOW);
-
- Action redAction = new ColorAction("Red",new ImageIcon("src/res/red-ball.gif"),Color.RED);
-
- Action exitAction = new AbstractAction("Exit",new ImageIcon("src/res/exit.gif")){
-
- public void actionPerformed(ActionEvent event){
-
- System.exit(0);
-
- }
-
- };
-
- // omitted here ......
- }
- }
目录结构如下:
D:\Learning\Java\workspace\CoreJavaV1>tree /F
Folder PATH listing for volume 新加卷
Volume serial number is 183E-0660
D:.
│ .classpath
│ .project
│ Instrument.class.violet
│
├─.settings
│ org.eclipse.jdt.core.prefs
│
├─bin
│ │
│ ├─ch09
│ │ SliderTest$1.class
│ │ SliderTest.class
│ │ SliderTestFrame$1.class
│ │ SliderTestFrame.class
│ │ ToolBarFrame$1.class
│ │ ToolBarFrame$ColorAction.class
│ │ ToolBarFrame.class
│ │ ToolBarTest$1.class
│ │ ToolBarTest.class
│ │
│ └─res
│ ace.gif
│ blue-ball.gif
│ exit.gif
│ jack.gif
│ king.gif
│ nine.gif
│ queen.gif
│ red-ball.gif
│ ten.gif
│ yellow-ball.gif
│
└─src
│
├─ch09
│ BorderTest.java
│ Calculator.java
│ CheckBoxTest.java
│ ComboBoxTest.java
│ MenuTest.java
│ RadioButtonTest.java
│ SliderTest.java
│ TextComponentTest.java
│ ToolBarTest.java
│
└─res
ace.gif
blue-ball.gif
exit.gif
jack.gif
king.gif
nine.gif
queen.gif
red-ball.gif
ten.gif
yellow-ball.gif
D:\Learning\Java\workspace\CoreJavaV1>
阅读(623) | 评论(0) | 转发(0) |