2016-01-21 45 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

相关问题