尝试使用Java将图像插入到JButton时发生错误
问题描述:
我正在尝试创建JButton,因为我想将图像插入到该图像中。所以我创造了这个代码不显示语法错误,但是当我尝试执行出现此异常:尝试使用Java将图像插入到JButton时发生错误
有人能告诉我如何将这个形象成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);
}
}
答
stacktrace指向我们在代码中实例化ImageIcon的地方。
Icon e=new ImageIcon(getClass().getResource("x.png"));
它可以通过正确寻址正在加载的资源来解决。如果x.png位于资源文件夹中,这将解决问题。
Icon e=new ImageIcon(getClass().getResource("/x.png"));
'x.png'图片的位置是什么? –
C:\ Users \ user \ Desktop \ leksione \ JAVA \ eclipse \ Detyra e kursit \ bin – Doen
它可能是文件不在您指向的位置,您没有区分大小写, t将文件位置添加到构建路径等。我建议您在本网站上搜索关于使用'getresource'加载资源的许多问题。如果显示类和文件所在的结构层次结构,它也会有所帮助。 – user1803551