2013-07-08 138 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"));