我正在嘗試創建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);
}
}
'x.png'圖片的位置是什麼? –
C:\ Users \ user \ Desktop \ leksione \ JAVA \ eclipse \ Detyra e kursit \ bin – Doen
它可能是文件不在您指向的位置,您沒有區分大小寫, t將文件位置添加到構建路徑等。我建議您在本網站上搜索關於使用'getresource'加載資源的許多問題。如果顯示類和文件所在的結構層次結構,它也會有所幫助。 – user1803551