2013-07-08 141 views
0

我正在尝试创建一个看起来像纸牌的切换按钮。无论我放置img文件夹的位置如何,都无法显示图像。我使用下面的代码。用图标切换按钮

final JFrame frame = new JFrame("Toggle button test"); 
frame.setSize(500, 300); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.getContentPane().setLayout(new FlowLayout()); 

ImageIcon icon = new ImageIcon("img/1.png"); 
JToggleButton jtbButton = new JToggleButton(icon); 

frame.add(jtbButton); 
frame.setVisible(true); 

回答

2

添加以下

System.out.println(new File("img/1.png").getAbsolutePath()); 

然后,确保该文件夹img存在于位置显示

旁白:通常你会想读从classpath的图像资源,而不是依赖在文件位置。这就是为什么从资源中读取更好,例如:

ImageIcon icon = new ImageIcon(MyClass.class.getResource("img/1.png"));