كيفية إدراج رمز الصورة في JButton في Java

يمكنك إضافة صورة أو رمز إلى زر في java< / b> في وقت إعلان JButton في المنشئ:

JButton b = JButton الجديد (رمز الرمز) ؛ 
< / pre>ou:

< pre class = "prettyprint lang-java" >JButton b = JButton جديد (نص سلسلة ، رمز أيقونة) ؛
< / pre>example:

< pre class = "prettyprint lang-java" >import java.awt.Dimension ؛
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class JButtonTest يمتد JFrame {

JButton b = JButton الجديد ("مفتوح" ، رمز الصورة الجديد ("icon.png") ؛

JButtonTest العام () {
إطار JFrame = JFrame جديد ("اختبار JFrame") ؛
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible (صحيح) ؛
b.setPreferredSize (البعد الجديد (150100)) ؛
frame.getContentPane().add(b);
frame.pack ();
}

الفراغ الثابت العام الرئيسي (سلسلة [] args) {
JButtonTest الجديد ();
}
}
< / pre> Output
إدراج صورة أو رمز في jbutton في جافا

الطريقة  setIcon

يمكن أيضا إدراج رمز بعد إنشاء الزر عن طريق استدعاء JButton.setIcon(ImageIcon img)الموجود في AbstractButton.

ImageIcon image = imageIcon ("icon.png"); 
b.setIcon (صورة) ؛
< / pre>< / div>

استيراد ImageIcon من classpath

لتحميل الصورة من مجلد ، استخدم الطريقة  ImageIO.read () < / span>. تأخذ هذه الطريقة مسار الصورة (المورد) كوسيطة مخزنة في مشروعنا. جاوة. الطريقة  getClass().getResource() أداة تحميل الفئة لتحميل المورد. هذا يعني أن هذا المورد يجب أن يكون في جذر مشروعك حتى يتم تحميله.