如何在菜单栏中导入图像

时间:2011-08-24 15:44:20

标签: java image swing jmenuitem jmenubar

我创建了一个简单的菜单栏,我不知道如何在可用空间中导入图像。

我的代码如下:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.IOException;

public class MyMenu extends JFrame {

    JMenuBar menubar;
    JMenu file, edit, contact, quit;
    JMenuItem exit, open, search, delete, registration, informations;

    public MyMenu() {
        setLayout(new FlowLayout());
        //___________________________ FILE __________________________________
        menubar = new JMenuBar();
        setJMenuBar(menubar);
        file = new JMenu("Αρχείο");
        menubar.add(file);
        open = new JMenuItem("Άνοιγμα πελατολογίου");
        file.add(open);
        event e1 = new event(); // Compiler Error
        open.addActionListener(e1);
        //__________________________________ EDIT ____________________________
        edit = new JMenu("Ενέργειες");
        menubar.add(edit);
        search = new JMenuItem("Αναζήτηση");
        edit.add(search);
        registration = new JMenuItem("Καταχώρηση");
        edit.add(registration);
        delete = new JMenuItem("Διαγραφή");
        edit.add(delete);
        //_________________________________ CONTACT __________________________
        contact = new JMenu("Επικοινωνία");
        menubar.add(contact);
        informations = new JMenuItem("Πληροφορίες");
        contact.add(informations);
        //___________________________________QUIT_____________________________
        quit = new JMenu("Έξοδος");
        menubar.add(quit);
        exit = new JMenuItem("Έξοδος");
        quit.add(exit);
        event e = new event(); // Compiler Error
        exit.addActionListener(e);
    }

    public class MyEvent implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }

        public void actionPerformed2(ActionEvent e1) {
            final SimpleTableDemo a = new SimpleTableDemo(); // Compiler Error
            javax.swing.SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    a.createAndShowGUI();
                }
            });
        }
    }

    public static void main(String[] args) throws IOException {
        MyMenu gui = new MyMenu();
        gui.getContentPane().add(panel); // Compiler Error
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(2400, 1900);
        gui.setVisible(true);
    }
}

它与班级Panel有关?如何利用可用空间并使用图像?

2 个答案:

答案 0 :(得分:4)

可以构建JMenuItem以显示图像。

ImageIcon icon = new ImageIcon("path_to_your_image");
JMenuItem item = new JMenuItem(icon);

答案 1 :(得分:4)

// Compiler Error

中对AddingImage / ImportImage的任何请求之前,请在此处发布没有来自Java Compilator的错误的Runnable代码(在代码中标有JMenuBar

必修教程

1)JMenu, JMenuBar, JMenuItems

2)Laying Out Components Within a Container

3)How to Write an Action Listener

4)How to Use Icons

5)最后将Image设为JMenuBar BackGround,你必须阅读一些内容 2D Graphics

6)此论坛上的示例herehere