实现mouseClicked()时出错 [英] Error in implementing mouseClicked()

查看:136
本文介绍了实现mouseClicked()时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()触发后,将lblStatuslbl.setVisible()设置为true.但是当我尝试它时,却得到了一些错误代码:

Hi! I am trying to implement mouseClicked() function in my code. As you can see, in the initialization, I've set the component lblStatuslbl.setVisible(false). Then, at public void mouseClicked(), when it is trigerred, I set for the lblStatuslbl.setVisible() to be true. But when I try it, instead I got some error code :

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)

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

Can anybody help me to deal with this problem? Thank you very much!

推荐答案

您正在通过在initialize方法中重新声明lblStatuslabel来隐藏它.这使它在类内为null,因此,当您调用lblStatuslabel.setVisible(true)时,将引发NPE:

You're shadowing the lblStatuslabel by re-declaring it in the initialize method. This leaves it null inside the class, and so when you call lblStatuslabel.setVisible(true), you'll throw a NPE:

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

解决方案:不要掩盖您的变量.所以代替这个:

Solution: don't shadow your variables. So instead of this:

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).您需要检查返回的stacktrace,找到引发NPE的行,并使用调试器或println语句仔细检查该行是否为空变量,例如:

More importantly, for long term benefit, you need to understand how to debug a NullPointerException (NPE). You need to inspect the stacktrace returned, find the line that throws the NPE, and carefully inspect the line for any null variables, using a debugger or println statements, such as:

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

然后搜索您的代码以查看为什么该变量为空.您一次又一次地遇到这些,请相信我.

Then search back into your code to see why the variable is null. You will run into these again and again, trust me.

编辑2

正如Dic19所说的那样,您不应使用MouseListener来监听按钮的按下,而应使用ActionListener或AbstractAction.后面的这些家伙是专门为按钮和菜单构建的,并且与MouseListener相比,它们的功能要好得多.如果将它们禁用,则该按钮将被适当禁用-对于MouseListener而言不是正确的.适当的侦听器将允许按钮与空格键一起使用-对于MouseListener而言并非如此.适当的侦听器会将actionCommand字符串传递给侦听器事件-对于MouseListener而言并非如此.

Also as Dic19 astutely mentions, you should not use a MouseListener to listen for button presses, but rather an ActionListener or an AbstractAction. These latter guys are built specifically for buttons and menus and work much better with them than a MouseListener. If they are disabled, then the button is appropriately disabled -- not true for a MouseListener. The appropriate listeners will allow the button to work with space bar presses -- not true for a MouseListener. The appropriate listeners will deliver the actionCommand String to the listener event -- not true for a MouseListener.

此外,您将要避免使用null布局和setBounds(...),因为这将导致创建刚性的GUI,该GUI在所有系统和屏幕分辨率(除了您自己的系统)上看起来都很糟糕,很难做到维护,调试和增强.而是了解并使用布局管理器.

Also, you'll want to avoid use of null layouts and setBounds(...) as this will lead to the creation of a rigid GUI that looks terrible on all systems and screen resolutions except for your own, that is difficult to maintain, debug and enhance. Instead learn about and use the layout managers.

这篇关于实现mouseClicked()时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆