2013-06-14 2 views
0

Хорошо, поверьте мне, когда я скажу вам, что я выполнил свою должную осмотрительность на этом. Я пытался отладить это в течение самого долгого времени, и я снова и снова просматривал код. Я проверил Stack Overflow, и никто не имел этой проблемы.Java Swing JMenu продолжает исчезать

Так что я пытаюсь создать меню в Java Swing. Это меню должно быть на JPanel. Я знаю, что по соглашению он должен быть на JFrame, но это было бы лучше для моих обстоятельств на JPanel. Проблема в том, что когда я нажимаю на меню «Функции» и пытаюсь навести мышь на один из элементов меню в нем, меню автоматически исчезает. Я попытался реализовать тот же код на JFrame, но произошло то же самое.

Итак, без дальнейших церемоний, вот код:

public static String[] getRGBInputsFromDialogBox(String title) { 
    JTextField rField = new JTextField(5); 
    JTextField gField = new JTextField(5); 
    JTextField bField=new JTextField(5); 

    JPanel myPanel = new JPanel(new FlowLayout()); 
    myPanel.add(new JLabel("R(x,y): ")); 
    myPanel.add(rField); 
    myPanel.add(Box.createHorizontalStrut(15)); // a spacer 
    myPanel.add(new JLabel("G(x,y): ")); 
    myPanel.add(gField); 
    myPanel.add(Box.createHorizontalStrut(15));//spacer 
    myPanel.add(new JLabel("B(x,y): ")); 
    myPanel.add(bField); 



    String[] myClasses=ClassInfo.getClasses();         
    // { { { { } , { } } , { { } , { } } } , { { { } , { } } , { { } , { } } } } 

    //Creating Menu Bar 
    JMenuBar menuBar=new JMenuBar(); 
     JMenu functionsMenu=new JMenu("Functions"); 
      JMenuItem[] classes=new JMenuItem[myClasses.length]; 
      for(int i=0;i<ClassInfo.classes.length;i++) { 
       String[][] classMethods=ClassInfo.showMethodsForClass(ClassInfo.classes[i]);// { {static} , {instance} } 
       final String className=ClassInfo.classes[i].getSimpleName(); 
       JMenuItem[] staticMethodsItem=new JMenuItem[classMethods[0].length]; 
       JMenuItem[] instanceMethodsItem=new JMenuItem[classMethods[1].length]; 
       JMenuItem staticMenuItem=new JMenuItem("Static methods"); 
       JMenuItem instanceMenuItem=new JMenuItem("Instance methods"); 
       JMenu staticMenu=new JMenu(); 
       staticMenuItem.add(staticMenu); 
       JMenu instanceMenu=new JMenu(); 
       instanceMenuItem.add(instanceMenu); 

       for(int a=0;a<classMethods[0].length;a++) { 
        final String methodName=classMethods[0][a]; 
        staticMethodsItem[a]=new JMenuItem(methodName); 
        staticMethodsItem[a].addActionListener(new ActionListener() { 
         public void actionPerformed(ActionEvent e) { 
          ClassInfo.copyToClipBoard(ClassInfo.staticWriteableString(methodName,className)); 
         } 
        }); 
        staticMenu.add(staticMethodsItem[a]); 
       } 

       for(int a=0;a<classMethods[1].length;a++) { 
        final String methodName=classMethods[1][a]; 
        instanceMethodsItem[a]=new JMenuItem(methodName); 
        instanceMethodsItem[a].addActionListener(new ActionListener() { 
         public void actionPerformed(ActionEvent e) { 
          ClassInfo.copyToClipBoard(ClassInfo.instanceWriteableString(methodName)); 
         } 
        }); 
        instanceMenu.add(instanceMethodsItem[a]); 
       } 

       classes[i]=new JMenuItem(className); 
       JMenu methodTypeMenu=new JMenu(); 
       methodTypeMenu.add(staticMenuItem); //add static method submenu to the new class submenu 
       methodTypeMenu.add(instanceMenuItem);//add instance method submenu to the new class submenu 
       classes[i].add(methodTypeMenu); //Make the new class a submenu 
       functionsMenu.add(classes[i]); //Add a new class in the functions menu 
      } 
    menuBar.add(functionsMenu); 
    myPanel.add(menuBar); 

    int result = JOptionPane.showConfirmDialog(null, myPanel, title, JOptionPane.OK_CANCEL_OPTION); 
    if (result == JOptionPane.OK_OPTION) { 
     String[] arr= {rField.getText(),gField.getText(),bField.getText()}; 
     return arr; 
    } 
    return null; 
} 

Его совсем немного, я знаю. Будем очень благодарны за любую помощь. Большое спасибо!

EDIT: По желанию, вот мой CourseInfo класс:

public class ClassInfo { 

    public static Class<?>[] classes={Outputer.class,Vector3.class}; 
/* 
    public static void main(String[] args) { 
     System.out.println(classes[0].getMethods()[4].toGenericString()); 
     //public static int Outputer.fib(int) for static methods 
     //public double Outputer.getOutputB(int,int) for instance methods 
    } 
*/ 
    public static String[] getClasses() { 
     final JFrame classesFrame=new JFrame("Select a Class You want to Use"); 
     String[] classNames=new String[classes.length]; 
     for(int i=0;i<classes.length;i++) { 
      classNames[i]=classes[i].getName(); 
     } 
     return classNames; 
/* 
     SpinnerListModel listModel=new SpinnerListModel(classNames); 
     JPanel spinnerPanel= new JPanel(); 
     JPanel buttonPanel=new JPanel(); 
     JLabel spinnerLabel=new JLabel("Choose a Class Whose Methods You Want to Inspect"); 
     final JSpinner classSpinner = new JSpinner(listModel); 
     spinnerPanel.add(spinnerLabel); 
     spinnerPanel.add(classSpinner); 

     JButton inspectButton=new JButton("Inspect Methods"); 
     buttonPanel.add(inspectButton); 

     inspectButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       for(int i=0;i<classes.length;i++) { 
        if(classes[i].getName().equals(classSpinner.getValue())) { 
         showMethodsForClass(classes[i]); 
         classesFrame.dispose(); 
         break; 
        } 
       } 
      } 
     }); 

     classesFrame.add(spinnerPanel); 
     classesFrame.add(buttonPanel); 
     classesFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     classesFrame.pack(); 
     classesFrame.setVisible(true); 
*/ 
    }//End Of Method---------------------------------------------------------------------------------------------------------------- 

    public static String[][] showMethodsForClass(Class<?> myClass) { 
     final String className=myClass.getSimpleName(); 
     Method[] methods=myClass.getMethods(); 
     String[] staticMethodStrings1=new String[methods.length]; 
     String[] instanceMethodStrings1=new String[methods.length]; 
     int statCount=0,instCount=0; 
     for(int i=0;i<methods.length;i++) { 
      String method=methods[i].toGenericString(); 
      System.out.println(method); //For Debugging 
      if(!method.contains("private") && !method.contains("java.")) { 
       if(methodIsStatic(method)) { 
        staticMethodStrings1[statCount]=method; 
        statCount++; 
       } else { 
        instanceMethodStrings1[instCount]=method; 
        instCount++; 
       } 
      } 
     } //End of for loop 

     String[] staticMethods=new String[statCount]; 
     String[] instanceMethods=new String[instCount]; 

     for(;statCount>0;statCount--) { 
      staticMethods[statCount-1]=staticMethodStrings1[statCount-1]; 
     } 

     for(;instCount>0;instCount--) { 
      instanceMethods[instCount-1]=instanceMethodStrings1[instCount-1]; 
     } 
     String[][] arr= {staticMethods,instanceMethods}; 
     return arr; 
/*  JFrame frame=new JFrame("Select a Method to Copy"); 
     frame.setLayout(new GridLayout()); 

     JPanel staticPanel=new JPanel(); 
     JPanel instancePanel=new JPanel(); 
     final JComboBox staticMethodsBox=new JComboBox(staticMethods); 
     final JComboBox instanceMethodsBox=new JComboBox(instanceMethods); 
     JButton copyStaticButton=new JButton("Copy this Static Method"); 
     JButton copyInstanceButton=new JButton("Copy this Instance Method"); 

     copyStaticButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       copyToClipBoard(staticWriteableString((String)staticMethodsBox.getSelectedItem(),className)); 
      } 
     }); 

     copyInstanceButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       copyToClipBoard(instanceWriteableString((String)staticMethodsBox.getSelectedItem())); 
      } 
     }); 


     staticPanel.add(staticMethodsBox); 
     staticPanel.add(copyStaticButton); 

     instancePanel.add(instanceMethodsBox); 
     instancePanel.add(copyInstanceButton); 

     frame.add(staticPanel); 
     frame.add(instancePanel); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.pack(); 
     frame.setVisible(true); 
*/  


    }//End Of Method---------------------------------------------------------------------------------------------------------------- 

    private static boolean methodIsStatic(String methodString) { 
     return methodString.contains("static "); 
    }//End Of Method---------------------------------------------------------------------------------------------------------------- 

    //public static int Outputer.fib(int) for static methods 
    //public double Outputer.getOutputB(int,int) for instance methods 

    public static String staticWriteableString(String methodStr,String className) { 
     return methodStr.substring(methodStr.indexOf('.')-className.length()); 
    } 

    public static String instanceWriteableString(String methodStr) { 
     return methodStr.substring(methodStr.indexOf('.')); 
    } 

    public static void copyToClipBoard(String myString) { 
     StringSelection stringSelection = new StringSelection (myString); 
     Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); 
     clpbrd.setContents (stringSelection, null); 
    } 

}//End of Class--------------------------------------------------------------------------------------------------------------------- 
+0

Вы очень близки к SSCCE. Если вы вставляете содержимое класса ClassInfo, я мог бы взглянуть и вернуться. – sethu

+0

@sethu уверен, проблем нет, вот оно! Заранее спасибо – sourdesi

ответ

1

Я думаю, что я понял проблему. Вы смешиваетесь с JMenu и JMenuItem. Это структура:

JMenuBar имеет JMenu/JMenuItem имеет JMenu/JMenuItem

Изменить ваш внутренний цикл к этому, и он должен работать:

JMenuBar menuBar=new JMenuBar(); 
JMenu functionsMenu=new JMenu("Functions"); 
JMenuItem[] classes=new JMenuItem[myClasses.length]; 
for(int i=0;i<ClassInfo.classes.length;i++) { 
    String[][] classMethods=ClassInfo.showMethodsForClass(ClassInfo.classes[i]);// { {static} , {instance} } 
    final String className=ClassInfo.classes[i].getSimpleName(); 
    JMenuItem[] staticMethodsItem=new JMenuItem[classMethods[0].length]; 
    JMenuItem[] instanceMethodsItem=new JMenuItem[classMethods[1].length]; 
    JMenu staticMenu=new JMenu("Static Methods"); 
    JMenu instanceMenu=new JMenu("Instance Methods"); 

    for(int a=0;a<classMethods[0].length;a++) { 
     final String methodName=classMethods[0][a]; 
     staticMethodsItem[a]=new JMenuItem(methodName); 
     staticMethodsItem[a].addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       ClassInfo.copyToClipBoard(ClassInfo.staticWriteableString(methodName,className)); 
      } 
     }); 
     staticMenu.add(staticMethodsItem[a]); 
    } 

    for(int a=0;a<classMethods[1].length;a++) { 
     final String methodName=classMethods[1][a]; 
     instanceMethodsItem[a]=new JMenuItem(methodName); 
     instanceMethodsItem[a].addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       ClassInfo.copyToClipBoard(ClassInfo.instanceWriteableString(methodName)); 
      } 
     }); 
     instanceMenu.add(instanceMethodsItem[a]); 
    } 

    classes[i]=new JMenu(className); 
    classes[i].add(staticMenu); //add static method submenu to the new class submenu 
    classes[i].add(instanceMenu);//add instance method submenu to the new class submenu 
    functionsMenu.add(classes[i]); //Add a new class in the functions menu 
} 
menuBar.add(functionsMenu); 
+0

Удивительный! Спасибо, он отлично поработал! Я предполагаю, что проблема заключалась в том, что после двух внутренних циклов я пытался добавить JMenuItem для каждого класса, а затем добавить еще один объект меню для каждого из JMenuItems. Я должен был добавить элемент меню для каждого класса в меню функций. Сначала все немного сбивает с толку, но я думаю, что теперь понимаю, спасибо вам! – sourdesi