簡體   English   中英

嘗試使用Java將圖像插入JButton時出錯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM