简体   繁体   English

尝试使用Java将图像插入JButton时出错

[英]Error when trying to insert images into JButton using Java

I'm trying to create a JButton because I want to insert an image into that. 我试图创建一个JButton,因为我想在其中插入一个图像。 So I've created this code which doesn't show syntax errors but when I try to execute this exception appears: 因此,我创建了以下代码,该代码不显示语法错误,但是当我尝试执行此异常时出现:

在此处输入图片说明

Can someone show me how to insert this image into that JButton? 有人可以告诉我如何将此图像插入该JButton吗? Here is my code: 这是我的代码:

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);
 }
}

The stacktrace points us to the place where ImageIcon is being instantiated in the code. stacktrace将我们指向在代码中实例化ImageIcon的位置。

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

It can be fixed by correctly addressing the resource that is being loaded. 可以通过正确寻址正在加载的资源来解决此问题。 If the x.png is residing in the resources folder, this will fix the problem. 如果x.png位于资源文件夹中,则可以解决此问题。

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

For sure try this 当然可以试试这个

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

with import javax.imageio.*; 使用import javax.imageio。*;

in your imports 在你的进口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM