如何将menuitems带到java中所有其他组件之上?

时间:2012-05-30 07:05:08

标签: swing

我在java中创建了动态menuitem,其中子菜单是从点击了menuitem的类别的数据库创建的。在相同的形式我有其他组件列表来查看结果。现在我的问题是创建的菜单项隐藏在此jlist后面。我想知道如何在其他组件上面显示这些菜单项。

1 个答案:

答案 0 :(得分:2)

因为,我真的不知道,您在JMenuBar上添加JFrame的确切位置,意味着要使用哪个代码。当您向JMenuBar添加菜单和所有菜单并将其添加到JFrame时,只需使用frameObject.revalidate() for JDK 1.7 or above For JDK 1.6 or below use frameObject.getContentPane().revalidate()frame.repaint()即可。以下是一个供您理解的示例程序:

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

public class DrawingExample
{
    private int x;
    private int y;
    private String text;
    private DrawingBase canvas;

    private void displayGUI()
    {
        final JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        JMenuItem menuItem = new JMenuItem("Open");

        menu.add(menuItem);
        menuBar.add(menu);

        final JFrame frame = new JFrame("Drawing Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        canvas = new DrawingBase();
        canvas.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent me)
            {
                text = "X : " + me.getX() + " Y : " + me.getY();
                x = me.getX();
                y = me.getY();
                canvas.setValues(text, x, y);
                frame.setJMenuBar(menuBar);
                frame.revalidate();
                frame.repaint();
            }
        }); 

        frame.setContentPane(canvas);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);     
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new DrawingExample().displayGUI();
            }
        });
    }
}

class DrawingBase extends JPanel
{
    private String clickedAt = "";
    private int x = 0;
    private int y = 0;

    public void setValues(String text, int x, int y)
    {
        clickedAt = text;
        this.x = x;
        this.y = y;
        repaint();
    }

    public Dimension getPreferredSize()
    {
        return (new Dimension(500, 400));
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawString(clickedAt, x, y);
    }
}