2012-05-30 20 views
1

我在java中創建了動態菜單項,其中子菜單是從其菜單項被點擊的那個類別的數據庫中創建的。在相同的形式,我有其他組件列表來查看結果。現在我的問題是創建的菜單項隱藏在這個jlist後面。我想知道如何將這些菜單項放在其他組件的上方。如何將menuitems的所有其他組件放在java中?

回答

2

因爲,我真的不知道,你在哪裏加JMenuBar你的JFrame,意思是說使用哪個代碼。當您將菜單全部添加到您的JMenuBar並將其添加到您的JFrame時,只需使用frameObject.revalidate() for JDK 1.7 or aboveFor 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); 
    } 
} 
相關問題