Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

java - Error in implementing 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);
    }
}

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";
   }
}

do:

public class Foo {
   private String bar;

   public Foo() {
      initialize();
   }

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

Edit

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.


Edit 2

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...