【问题标题】:jMenuBar does not show any of its jmenuitems in swingjMenuBar 不显示它的任何 jmenuitems 摆动
【发布时间】:2015-07-23 13:45:36
【问题描述】:

我在 Swing 的菜单栏中添加了一些菜单项。当我运行程序时,菜单栏没有显示任何JMenuItems,而是抛出一个NullPointerException

当我在 AWT 中创建菜单栏时,它工作得很好。我没有在这个程序中添加任何功能。我使用 NetBeans,只是将这些 Swing 组件拖放到我的面板中。请帮忙!

public class test extends javax.swing.JFrame {

/** Creates new form test */
public test() {
    initComponents();
}

/** This method is called from within the constructor to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jMenuItem1 = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setName("Form"); // NOI18N

    jPanel1.setName("jPanel1"); // NOI18N

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 279, Short.MAX_VALUE)
    );

    jMenuBar1.setName("jMenuBar1"); // NOI18N

    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flupertech.FlupertechApp.class).getContext().getResourceMap(test.class);
    jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
    jMenu1.setName("jMenu1"); // NOI18N

    jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
    jMenuItem1.setName("jMenuItem1"); // NOI18N
    jMenu1.add(jMenuItem1);

    jMenuBar1.add(jMenu1);

    jMenu2.setText(resourceMap.getString("jMenu2.text")); // NOI18N
    jMenu2.setName("jMenu2"); // NOI18N
    jMenuBar1.add(jMenu2);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new test().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}

【问题讨论】:

    标签: java swing exception jmenubar


    【解决方案1】:

    错误来源是资源加载不起作用:

    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop
        .application.Application
        .getInstance(flupertech.FlupertechApp.class).getContext()
        .getResourceMap(test.class);
    jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
    jMenu1.setName("jMenu1"); // NOI18N
    
    jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
    jMenuItem1.setName("jMenuItem1"); // NOI18N
    jMenu1.add(jMenuItem1);
    
    jMenuBar1.add(jMenu1);
    
    jMenu2.setText(resourceMap.getString("jMenu2.text")); // NOI18N
    

    如果我将其更改为:

    jMenu1.setText("b"); // NOI18N
    jMenu1.setName("jMenu1"); // NOI18N
    
    jMenuItem1.setText("c"); // NOI18N
    jMenuItem1.setName("jMenuItem1"); // NOI18N
    jMenu1.add(jMenuItem1);
    
    jMenuBar1.add(jMenu1);
    
    jMenu2.setText("a"); // NOI18N
    jMenu2.setName("jMenu2"); // NOI18N
    jMenuBar1.add(jMenu2);
    

    它运行良好,您可能想找出您的 ResourceMap 或其方法之一返回 null 的原因。

    【讨论】:

    • 好的,我明白你的意思。但是如何检查我的 ResourceMap 的属性?
    • 只需在该行设置一个断点,然后用调试器检查什么是空的。
    【解决方案2】:

    现在可以了。只需要创建一个对象。所以我创建了一个新的 jForm 并使用 jButton 调用它。所以它传递了一个这种形式的对象,现在它工作得很好。

    【讨论】:

      【解决方案3】:
      from bs4 import BeautifulSoup
      import requests
      from contextlib import closing
      from selenium.webdriver import Chrome # pip install selenium
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.keys import Keys
      from selenium.common.exceptions import *
      import selenium 
      import os
      import re
      import csv
      
      import sys
      
      pPortalBS = requests.get("https://sapeadfs.sapient.com/adfs/ls?wa=wsignin1.0&wtrealm=urn%3asamlcolo%3apeopleportal&wctx=https%3a%2f%2fpeopleportal2.sapient.com%2fmy%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F")
      pPortal = BeautifulSoup(pPortalBS.content,"html5lib")
      
      #print pPortal
      
      chromedriver = "C:/chromedriver"
      os.environ["webdriver.chrome.driver"] = chromedriver
      #driver = webdriver.Chrome(chromedriver)
      #12,18,30,39,48,76,78
      i=0
      logged_in_flag = 0
      with closing(Chrome(chromedriver)) as driver:
      
      
          driver.get("https://www.cdnplanet.com/tools/cdnfinder")
      
          #button = driver.find_element_by_id('idp')
          page_source = driver.page_source
          #page_source
      
          # wait for the page to load
          element = WebDriverWait(driver, 10).until(
          EC.visibility_of_element_located((By.ID, "cdn-cdnfinderfull"))
          )
          # store it to string variable
          page_source = driver.page_source
      
          #logging in
      
          urls=["http://google.com","https://localhost.xxxxxx","http://twitter.com","http://facebook.com"]
          for url in urls:
              try:
                  usernameInput = driver.find_element_by_name("cdn")
                  usernameInput.clear()
                  usernameInput.send_keys(url)
      
                  button = driver.find_elements_by_xpath(".//*/button[@class='btn btn-large']")
      
                  button[0].click()
                  element = WebDriverWait(driver, 10).until(
                  EC.visibility_of_element_located((By.ID, "cdnfinderfull-results"))
                  )
      
                  with closing(open("Test.csv", "a")) as ofile:   
                      fileWriter = csv.writer(ofile)
                      page_source = driver.page_source
                      pPortal = BeautifulSoup(page_source, "html5lib")
                      table = pPortal.find("table")
      
                      print table
              except:
                  print ("NO!!!!")
      

      【讨论】:

      • 请解释您发布的代码。为什么它有效,操作者在做什么,等等......
      • DevTools 监听 ws://127.0.0.1:51063/devtools/browser/a5199eb1-f069-4d42-8176-34487a454077 [0706/164153.496:ERROR:gl_surface_egl.cc(844)] eglInitialize D3D9失败并出现错误 EGL_NOT_INITIALIZED [0706/164153.498:ERROR:gl_initializer_win.cc(232)] GLSurfaceEGL::InitializeOneOff 失败。 [0706/164153.521:ERROR:viz_main_impl.cc(199)] 由于初始化期间出现错误而退出 GPU 进程 [8364:11748:0706/164154.446:ERROR:gpu_process_transport_factory.cc(1017)] 丢失 UI 共享上下文。 ERROR:command_buffer_proxy_impl.cc(114)] ContextResult::kFatalFailure: 共享内存句柄无效
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多