开发者

Java Null Pointer Exception on JLIST

开发者 https://www.devze.com 2023-01-07 10:54 出处:网络
OK so I\'m trying to output the current string from an array that was put into a list... However when I click on the list I get a NullPointerException... :\\

OK so I'm trying to output the current string from an array that was put into a list... However when I click on the list I get a NullPointerException... :\

Help? :)

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class lisTry extends JApplet implements MouseListener {

public static String newline;开发者_运维百科
public static JList list;

    public void init() {

            DefaultListModel listModel = new DefaultListModel();
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Alan Sommerer");

            JList list = new JList(listModel);


        this.getContentPane().add(list);

        list.addMouseListener(this);

        String newline = "\n";

        list.setVisible(true);

    }

    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) {
       int index = list.getSelectedIndex();
       System.out.println("You clicked on: " + index);
    }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }

    public void paint(Graphics g) {

    } 
}

Thank you.


Change this line:

JList list = new JList(listModel);

into this line:

list = new JList(listModel);

You are creating a local variable list in your constructor and thus hide the list field of your class. So the field lisTry.list stays null, hence the NullPointerException.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号