Learn Typing Programming Basics SQL HTML CSS JavaScript Python C++ Java JavaFX Swing Computer Fundamentals English English Conversations Problem Solving

Swing طريقة وضع أيقونة للـ JMenuItem

المثال التالي يعلمك طريقة وضع أيقونات لعناصر القائمة.

في البداية قمنا بإنشاء مجلد خاص لوضع الأيقونات التي نريد عرضها في البرنامج كما في الصورة التالية.

⇓ تحميل مجلد الصور


مثال

Main.java
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.ImageIcon;
 
public class Main {
 
    public static void main(String[] args) {
 
        JFrame frame = new JFrame("JMenuBar demo");              // أي قمنا بإنشاء نافذة مع وضع عنوان لها JFrame هنا أنشأنا كائن من الكلاس
        frame.setSize(500, 250);                                 // هنا قمنا بتحديد حجم النافذة. عرضها 500 و طولها 250
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    // هنا جعلنا زر الخروج من النافذة يغلق البرنامج
 
        // هنا قمنا بتعريف شريط القوائم
        JMenuBar menuBar = new JMenuBar();
 
        // هنا قمنا بتعريف قائمة واحدة
        JMenu menu = new JMenu("Menu");
 
        // هنا قمنا بتعريف 4 عناصر
        JMenuItem newFile = new JMenuItem("New", new ImageIcon(Main.class.getResource("images/new-file-icon.png")));
        JMenuItem open = new JMenuItem("Open", new ImageIcon(Main.class.getResource("images/open-icon.png")));
        JMenuItem save = new JMenuItem("Save", new ImageIcon(Main.class.getResource("images/save-icon.png")));
        JMenuItem exit = new JMenuItem("Exit", new ImageIcon(Main.class.getResource("images/exit-icon.png")));
 
        // هنا قمنا بوضع القائمة في شريط القوائم
        menuBar.add(menu);
 
        // هنا قمنا بوضع جميع العناصر في القائمة
        menu.add(newFile);
        menu.add(open);
        menu.add(save);
        menu.addSeparator(); // هنا أضفنا خط فاصل
        menu.add(exit);
 
        // frame هنا قمنا بوضع شريط القوائم في الـ
        frame.setJMenuBar(menuBar);
 
        // مرئية frame هنا جعلنا الـ
        frame.setVisible(true);
 
    }
 
}
		

ستظهر لك النافذة التالية عند التشغيل.

طريقة إضافة أيقونات للعناصر JMenuItem في جافا

الدورات

أدوات مساعدة

أقسام الموقع

دورات
مقالات كتب مشاريع أسئلة