实现mouseClicked()时出错

时间:2014-11-13 15:46:45

标签: java swing nullpointerexception mouselistener

public class ControllerGui {

private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JLabel lblStatuslabel;
public JLabel lblPortlabel;
public JLabel lblIplabel;


/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ControllerGui window = new ControllerGui();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ControllerGui() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
public void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.setBorder(null);
    tabbedPane.setBounds(6, 6, 438, 570);
    frame.getContentPane().add(tabbedPane);

    JPanel panel = new JPanel();
    panel.setBorder(null);
    tabbedPane.addTab("Connection", null, panel, null);
    panel.setLayout(null);

    JLabel lblTcpipConnection = new JLabel("TCP/IP Connection");
    lblTcpipConnection.setBounds(6, 6, 91, 13);
    lblTcpipConnection.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
    panel.add(lblTcpipConnection);

    JLabel lblNewLabel = new JLabel("IP Address :");
    lblNewLabel.setBounds(17, 24, 74, 16);
    panel.add(lblNewLabel);

    textField = new JTextField();
    textField.setBounds(97, 18, 165, 28);
    panel.add(textField);
    textField.setColumns(10);

    JButton btnNewButton = new JButton("Connect");
    btnNewButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("Clicked");
            lblStatuslabel.setVisible(true);
        }
    });
    btnNewButton.setBounds(268, 18, 151, 29);
    panel.add(btnNewButton);

    JLabel lblPort = new JLabel("Port :");
    lblPort.setBounds(58, 58, 33, 16);
    panel.add(lblPort);

    textField_1 = new JTextField();
    textField_1.setBounds(97, 52, 165, 28);
    panel.add(textField_1);
    textField_1.setColumns(10);

    JButton btnDisconnect = new JButton("Disconnect");
    btnDisconnect.setBounds(268, 52, 151, 29);
    panel.add(btnDisconnect);

    JLabel lblConnectionStatus = new JLabel("Connection Status");
    lblConnectionStatus.setBounds(6, 86, 91, 12);
    lblConnectionStatus.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
    panel.add(lblConnectionStatus);

    JLabel lblStatus = new JLabel("Status");
    lblStatus.setBounds(52, 103, 39, 16);
    panel.add(lblStatus);

    JLabel lblStatuslabel = new JLabel("CONNECTED!");
    lblStatuslabel.setForeground(Color.GREEN);
    lblStatuslabel.setVisible(false);
    lblStatuslabel.setBounds(97, 103, 91, 16);
    panel.add(lblStatuslabel);

    JLabel lblNewLabel_1 = new JLabel("IP Status");
    lblNewLabel_1.setBounds(37, 124, 54, 16);
    panel.add(lblNewLabel_1);

    JLabel lblIplabel = new JLabel("192.168.110.1");
    lblIplabel.setVisible(false);
    lblIplabel.setBounds(97, 124, 109, 16);
    panel.add(lblIplabel);

    JLabel lblPortStatus = new JLabel("Port Status");
    lblPortStatus.setBounds(23, 145, 68, 16);
    panel.add(lblPortStatus);

    JLabel lblPortlabel = new JLabel("1234");
    lblPortlabel.setVisible(false);
    lblPortlabel.setBounds(97, 145, 83, 16);
    panel.add(lblPortlabel);

    JLabel lblLog = new JLabel("Log");
    lblLog.setBounds(6, 166, 17, 13);
    lblLog.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
    panel.add(lblLog);

    JTextArea textArea = new JTextArea();
    textArea.setBounds(6, 191, 401, 327);
    panel.add(textArea);

    JSeparator separator = new JSeparator();
    separator.setBounds(100, 7, 315, 13);
    panel.add(separator);

    JSeparator separator_1 = new JSeparator();
    separator_1.setBounds(100, 88, 80, 6);
    panel.add(separator_1);

    JSeparator separator_2 = new JSeparator();
    separator_2.setBounds(25, 168, 390, 12);
    panel.add(separator_2);

    JLabel lblNewLabel_2 = new JLabel("Modbus ID");
    lblNewLabel_2.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
    lblNewLabel_2.setBounds(204, 86, 54, 16);
    panel.add(lblNewLabel_2);

    JSeparator separator_3 = new JSeparator();
    separator_3.setBounds(261, 88, 151, 12);
    panel.add(separator_3);

    JLabel lblSlaveId = new JLabel("ID :");
    lblSlaveId.setBounds(204, 124, 33, 16);
    panel.add(lblSlaveId);

    textField_2 = new JTextField();
    textField_2.setBounds(232, 118, 74, 28);
    panel.add(textField_2);
    textField_2.setColumns(10);

    JButton btnNewButton_1 = new JButton("CONNECT");
    btnNewButton_1.setBounds(316, 104, 91, 58);
    panel.add(btnNewButton_1);

    JPanel panel_1 = new JPanel();
    tabbedPane.addTab("Controller", null, panel_1, null);
    }
}

嗨!我正在努力实施     的mouseClicked() 函数在我的代码中。如您所见,在初始化中,我设置了组件lblStatuslbl.setVisible(false)。然后,在public void mouseClicked(),当它被trigerred时,我设置为lblStatuslbl.setVisible()为true。但是当我尝试它时,我得到了一些错误代码:

Clicked
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ControllerGui$2.mouseClicked(ControllerGui.java:105)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
    at java.awt.Component.processMouseEvent(Component.java:6519)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
    at java.awt.Component.processEvent(Component.java:6281)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

有人可以帮我解决这个问题吗?非常感谢你!

1 个答案:

答案 0 :(得分:2)

你通过在initialize方法中重新声明它来影响lblStatuslabel。这使得它在类中保持为null,因此当您调用lblStatuslabel.setVisible(true)时,您将抛出一个NPE:

    public void mouseClicked(MouseEvent e) {
        System.out.println("Clicked");
        lblStatuslabel.setVisible(true);  // ***** here *****
    }

解决方案:不要遮蔽你的变量。所以不要这样:

public class Foo {
   private String bar; // this variable stays null

   public Foo() {
      initialize();
   }

   public void intialize() {
      // this initialize a *local* variable
      String bar = "baz";
   }
}

做的:

public class Foo {
   private String bar;

   public Foo() {
      initialize();
   }

   public void intialize() {
      bar = "baz"; // note the difference?
   }
}

修改

更重要的是,为了获得长期利益,您需要了解如何调试NullPointerException(NPE)。您需要检查返回的堆栈跟踪,找到抛出NPE的行,并使用调试器或println语句仔细检查任何空变量的行,例如:

System.out.println("is lblStatuslabel null?: " + (lblStatuslabel == null));

然后搜索回代码,看为什么变量为null。你一次又一次地遇到这些,相信我。


修改2

同样Dic19精明地提到,你不应该使用MouseListener来监听按钮按下,而是使用ActionListener或AbstractAction。后面这些人专门为按钮和菜单而构建,并且比MouseListener更好地使用它们。如果它们被禁用,则按钮被适当禁用 - 对于MouseListener不适用。适当的监听器将允许按钮与空格键按下 - 对于MouseListener不适用。适当的侦听器将actionCommand String传递给侦听器事件 - 对于MouseListener而言不是这样。

此外,您还希望避免使用null布局和setBounds(...),因为这会导致创建一个严格的GUI,除了您自己的系统和屏幕分辨率外,它们看起来很糟糕,这很难维护,调试和增强。而是学习并使用布局管理器。