2016-01-21 126 views
0

我正在嘗試創建JButton,因爲我想將圖像插入到該圖像中。所以我創造了這個代碼不顯示語法錯誤,但是當我嘗試執行出現此異常:嘗試使用Java將圖像插入到JButton時發生錯誤

enter image description here

有人能告訴我如何將這個形象成JButton的?這裏是我的代碼:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.event.*; 
import javax.swing.*; 
import java.util.Random; 

public class Background extends JFrame { 
private Random ran; 
private int value; 
private JButton b; 
private JButton c; 

public Background() { 

    super("ttile"); 
    ran = new Random(); 
    value = nextValue(); 

    setLayout(new FlowLayout()); 
    b = new JButton("ROLL THE DICES"); 
    b.setForeground(Color.WHITE); //ndryshon ngjyren e shkrimit 
    b.setBackground(Color.YELLOW); 
    // b.setBounds(100, 100, 20, 70); 
    add(b, BorderLayout.SOUTH); 
    Icon e = new ImageIcon(getClass().getResource("x.png")); 
    c = new JButton("hey", e); 
    add(c); 

    thehandler hand = new thehandler(); //konstruktori i handler merr nje instance te Background 
    b.addActionListener(hand); 
    c.addActionListener(hand); 

} 
private class thehandler implements ActionListener { 

    public void actionPerformed(ActionEvent event) { 

    } 
} 

public static void main(String[] args) { 

    Background d = new Background(); 

    d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    d.getContentPane().setBackground(Color.GREEN); 
    d.setSize(3000, 3000); 

    d.setVisible(true); 
} 
} 
+0

'x.png'圖片的位置是什麼? –

+0

C:\ Users \ user \ Desktop \ leksione \ JAVA \ eclipse \ Detyra e kursit \ bin – Doen

+0

它可能是文件不在您指向的位置,您沒有區分大小寫, t將文件位置添加到構建路徑等。我建議您在本網站上搜索關於使用'getresource'加載資源的許多問題。如果顯示類和文件所在的結構層次結構,它也會有所幫助。 – user1803551

回答

0

stacktrace指向我們在代碼中實例化ImageIcon的地方。

Icon e=new ImageIcon(getClass().getResource("x.png")); 

它可以通過正確尋址正在加載的資源來解決。如果x.png位於資源文件夾中,這將解決問題。

Icon e=new ImageIcon(getClass().getResource("/x.png")); 
+0

Does'nt幫助此解決方案。 – Doen

+0

你能描述你的項目結構和資源文件x.png所在的路徑嗎?你是否在使用maven構建和打包? –

+0

C:\ Users \ user \ Desktop \ leksione \ JAVA \ eclipse \ Detyra e kursit \ bin這是路徑。我正在使用packagigng – Doen

0

可以肯定嘗試這個

BufferedImage bim=null; 
    try { 
    bim=ImageIO.read(new File("c:/.../x.png")); 
    } 
    catch (Exception ex) { ex.printStackTrace(); }  
Icon e=new ImageIcon(bim); 

與進口javax.imageio中的*。

在您的導入中

+1

這需要文件在'C:/'驅動器 –

+0

的哪裏可以插入? – Doen

+0

代替Icon e = new ImageIcon(getClass()。getResource(「x.png」)); – gpasch

相關問題