[英]Error when trying to insert images into JButton using 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"));
当然可以试试这个
BufferedImage bim=null;
try {
bim=ImageIO.read(new File("c:/.../x.png"));
}
catch (Exception ex) { ex.printStackTrace(); }
Icon e=new ImageIcon(bim);
使用import javax.imageio。*;
在你的进口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.