Jlist help
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 24

Thread: Jlist help

  1. #1
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Question Jlist help

    So I'm working on a project which needs a JList that prints a different value than what the item says on the list. So when I use the following code:
    Code:
    String p;
    
    ...
    
    class quick1Listener implements ActionListener{
    
    public void actionPerformed(ActionEvent e) {
    JFrame frame = new JFrame("Arrangements");
    String[] aras = {"ANV", "NAV", "AVN", "VAN"};
    
    list = new JList(aras);
    list.setSelectedIndex(0);
    list.setSelectionMode(ListSelectionMo...
    list.addListSelectionListener(new listListener());
    JButton set = new JButton("Done");
    set.addActionListener(new setListener());
    frame.getContentPane().add(BorderLayo... list);
    frame.getContentPane().add(BorderLayo... set);
    frame.setSize(250,250);
    frame.setVisible(true);
    
    }
    
    ...
    
    class listListener implements ListSelectionListener{
    
    public void valueChanged(ListSelectionEvent e) {
    if(!e.getValueIsAdjusting()){
    String selection = (String) list.getSelectedValue();
    p = selection;
    }else{
    
    }
    
    }
    
    }
    How would I make it print something like "Adjective Noun Verb" instead of "ANV"? In other words how do I set a value to a particular item besides what it already says? Thanks in advance!

  2. #2
    Join Date
    Apr 2007
    Posts
    442

    Re: Jlist help

    So, you want the items in your String Array to populate the list, but something completely different to appear printed somewhere upon list selection event?

    Simple would be to have a map, where keys would be the short versions (such as ANV) and values would be the long ones (such as "Adjective noun verb"). Upon selection you get the short one, get the equalent long one from the map and print that.

    Or then again the model can contain any type of Objects. There is no restriction between what the model holds and how things are rendered. So you could have a class that holds the long one and the short one. For rendering purposes the short one is used, for selection purposes, you can cast the object and get to the long one.

  3. #3
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Talking Re: Jlist help

    Thanks! This really helps! Too bad I didn't know about Maps earlier =D

  4. #4
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    Okay I did it but since HashMap doesn't implement Collection JList won't take it because it doesn't implement Collection. At least this is what I think is wrong. If you can please help! Here's my code:

    Code:
    //Phrasebot is property of shakenearth.com
    //Code by Thomas Lisankie
    //You may not use any of this code
    //you may not distribute this program either
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    
    import java.io.*;
    import java.net.*;
    public class Phrasebot implements ActionListener {
    	
    	JTextArea midgui;
    	JButton phrasemaker;
    	Box boxleft;
    	
    	JTextField nounbox1;
    	JTextField nounbox2;
    	JTextField nounbox3;
    	
    	JTextField adjbox1;
    	JTextField adjbox2;
    	JTextField adjbox3;
    	
    	JTextField verbbox1;
    	JTextField verbbox2;
    	JTextField verbbox3;
    	
    	ArrayList<String> nouns = new ArrayList<String>();
    	ArrayList<String> adjectives = new ArrayList<String>();
    	ArrayList<String> verbs = new ArrayList<String>();
    	
    	JList list;
    
    	String a;
    	
    	JTextField savefield;
    	JButton save;
    	
    	
    	
    	String p;
    	
    	
    public static void main(String[] args){
    try{
    	
    	Phrasebot bot = new Phrasebot();
    bot.go();
    }catch(Error Ex){
    	Ex.printStackTrace();
    }
    }
    public void go() {
    	
    	
    	JPanel pcenter = new JPanel();
    	JFrame frame = new JFrame("Phrasebot");//makes a new JFrame called "Phrasebot"
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//sets the default close operation to EXIT_ON_CLOSE
    	boxleft = new Box(BoxLayout.Y_AXIS);
    	
    	
    	JPanel bigpanel = new JPanel();//makes a new JPanel called bigpanel
    	bigpanel.setLayout(new BoxLayout(bigpanel,BoxLayout.Y_AXIS));//sets bigpanel's default layout to BoxLayout
    	JPanel spacer = new JPanel();//makes a new JPanel called spacer
    	spacer.setLayout(new BoxLayout(spacer, BoxLayout.Y_AXIS));//sets spacer's layout to BoxLayout
    	JLabel label = new JLabel(" ");//makes a new JLabel
    	spacer.add(label);//adds label to spacer
    	bigpanel.add(spacer);//adds spacer to bigpanel
    	JPanel peast = new JPanel();//makes a new panel called peast
    	bigpanel.add(peast);//bigpanel adds peast
    	peast.setLayout(new  BoxLayout(peast,BoxLayout.Y_AXIS));//sets peast's layout to boxlayout
    	JButton morenoun = new JButton("Add a Noun");//makes a new button called more noun with the text "More Nouns"
    	morenoun.addActionListener(new morenounListener());//morenoun adds an actionlistener which is a morenounlistener()
    	peast.add(morenoun);//peast adds morenoun
    	JButton clearnoun = new JButton("Clear Nouns");//makes a new button called clearnoun with the text "Clear Nouns"
    	clearnoun.addActionListener(new clearnounListener());//clearnoun adds an actionlistener which is a clearnounlistener()
    	peast.add(clearnoun);//peast adds clearnoun
    	JLabel spacer2 = new JLabel(" ");//makes a new label called spacer2
    	peast.add(spacer2);//peast adds spacer2
    	JButton moreadj = new JButton("Add an Adjective");//makes a new button called moreadj with the text "More Adjectives"
    	moreadj.addActionListener(new moreadjListener());//moreadj adds an actionlistener which is a moreadjlistener()
    	peast.add(moreadj);//peast adds moreadj
    	JButton clearadj = new JButton("Clear Adjectives");//makes a new button called clearadj with the text "Cear Adjectives"
    	clearadj.addActionListener(new clearadjListener());//clearadj adds an actionlistener which is a clearadjlistener()
    	peast.add(clearadj);//peast adds clearadj
    	JLabel spacer3 = new JLabel(" ");//makes a new label called spacer3
    	peast.add(spacer3);//peast adds
    	JButton moreverb = new JButton("Add a Verb");//makes a new button called moreverb with the text "More Verbs"
    	moreverb.addActionListener(new moreverbListener());//moreverb adds an actionlistener which is a moreverblistener()
    	peast.add(moreverb);//peast adds moreverb
    	JButton clearverb = new JButton("Clear Verbs");//makes a new button called clearverb with the text "Clear Verbs"
    	clearverb.addActionListener(new clearverbListener());//clearverb adds an actionlistener which is a clearverbListener()
    	peast.add(clearverb);//peast adds clearverb
    	JLabel savespacer = new JLabel(" ");//makes a new label called savespacer
    	peast.add(savespacer);//peast adds savespacer
    	JButton savewords = new JButton("Save Words");//makes a new button called save words
    	savewords.addActionListener(new savewordsListener());//savewords adds an actionlistener which is a savewordsListener()
    	peast.add(savewords);//peast adds savewords
    	JButton savesession = new JButton("Save Phrases");//creates a new button called savesession with the text "Save Phrases"
    	savesession.addActionListener(new savesessionListener());//savesession adds an actionlistener which is a savesessionListener()
    	peast.add(savesession);//peast adds savesession
    	JLabel quickspacer = new JLabel(" ");//makes a new label called quickspacer
    	peast.add(quickspacer);//peast adds quickspacer
    	JButton quick1 = new JButton("Word Arrangement 1");//makes a new button called quick1 with the text "Quickie Button 1"
    	quick1.addActionListener(new quick1Listener());//
    	peast.add(quick1);
    	JButton quick2 = new JButton("Word Arrangement 2");
    	quick2.addActionListener(new quick2Listener());
    	peast.add(quick2);
    	JButton quick3 = new JButton("Word Arrangement 3");
    	quick3.addActionListener(new quick3Listener());//100
    	peast.add(quick3);
    	
    	JPanel pwest = new JPanel();
    	pwest.setLayout(new BoxLayout(pwest,BoxLayout.Y_AXIS));
    	JPanel bigpanel2 = new JPanel();
    	bigpanel2.add(pwest);
    	
    	
    	
    	Font midfont = new Font("Comic Sans MS", Font.BOLD, 18);
    	midgui = new JTextArea(10,20);
    	midgui.setEditable(false);
    	midgui.setLineWrap(true);
    	midgui.setFont(midfont);
    	JScrollPane scroll = new JScrollPane(midgui);
    	scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    	scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    	pcenter.add(scroll);
    	
    	
    	
    	
    	nounbox1 = new JTextField("Noun	");
    	nounbox2 = new JTextField("Noun	");
    	nounbox3 = new JTextField("Noun	");
    	JLabel spacer4 = new JLabel(" ");
    	pwest.add(nounbox1);
    	nounbox1.addActionListener(this);
    	pwest.add(nounbox2);
    	nounbox2.addActionListener(new nounbox2Listener());
    	pwest.add(nounbox3);
    	nounbox3.addActionListener(new nounbox3listener());
    	pwest.add(spacer4);
    	adjbox1 = new JTextField("Adjective  ");
    	adjbox2 = new JTextField("Adjective  ");
    	adjbox3 = new JTextField("Adjective  ");
    	JLabel spacer5 = new JLabel(" ");
    	pwest.add(adjbox1);
    	adjbox1.addActionListener(new adjbox1Listener());
    	pwest.add(adjbox2);
    	adjbox2.addActionListener(new adjbox2Listener());
    	pwest.add(adjbox3);
    	adjbox3.addActionListener(new adjbox3Listener());
    	pwest.add(spacer5);
    	verbbox1 = new JTextField("Verb  ");
    	verbbox2 = new JTextField("Verb  ");
    	verbbox3 = new JTextField("Verb  ");
    	pwest.add(verbbox1);
    	verbbox1.addActionListener(new verbbox1Listener());
    	pwest.add(verbbox2);
    	verbbox2.addActionListener(new verbbox2Listener());
    	pwest.add(verbbox3);
    	verbbox3.addActionListener(new verbbox3Listener());
    	JPanel psouth = new JPanel();
    	JPanel bigpanel3 = new JPanel();
    	bigpanel3.add(psouth);
    	phrasemaker = new JButton("Make A Phrase!");
    	phrasemaker.addActionListener(new phrasemakerListener());
    	psouth.add(phrasemaker);
    	boxleft.add(nounbox1);
    	boxleft.add(nounbox2);
    	boxleft.add(nounbox3);
    	Box.createVerticalGlue();
    	boxleft.add(adjbox1);
    	boxleft.add(adjbox2);
    	boxleft.add(adjbox3);
    Box.createVerticalGlue();
    	boxleft.add(verbbox1);
    	boxleft.add(verbbox2);
    	boxleft.add(verbbox3);
    	frame.setSize(800,600);//sets the size of the JFrame
    	frame.setVisible(true);//sets the ability to see the JFrame
    	
    	
    	frame.getContentPane().add(BorderLayout.EAST, bigpanel);
    	frame.getContentPane().add(BorderLayout.WEST, boxleft);
    	frame.getContentPane().add(BorderLayout.SOUTH, bigpanel3);
    	frame.getContentPane().add(BorderLayout.CENTER, scroll);
    
    }
    public void actionPerformed(ActionEvent e) {
    	
    	
    }
    class phrasemakerListener implements ActionListener{
    	public void actionPerformed(ActionEvent ev) {
    		try{	
    			
    		midgui.append(p + "\n ");
    		phrasemaker.setText("Make Another!");
    		}
    		catch(Exception ex){
    		ex.printStackTrace();	
    		}
    	}
    	
    }
    
    class morenounListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		nouns.add(nounbox1.getText());
    		nounbox1.setText("");
    		
    	}
    	
    }
    class clearnounListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class moreadjListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		adjectives.add(adjbox1.getText());
    		adjbox1.setText("");
    		
    	}
    	
    }
    class clearadjListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class moreverbListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		verbs.add(verbbox1.getText());
    		verbbox1.setText(""); 
    		
    	}
    	
    }
    class clearverbListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class savewordsListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		try{
    			FileOutputStream fileout = new FileOutputStream("words.pb");
    		ObjectOutputStream out = new ObjectOutputStream(fileout);
    		
    		out.writeObject(nouns);
    		out.close();
    		midgui.append("words saved");
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
    	}
    	
    }
    class savesessionListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 try{
    			 JFrame frame = new JFrame();
    			 savefield = new JTextField("Untitled.txt");
    			 JButton save = new JButton("Save");
    			 save.addActionListener(new savebuttonListener());
    			 frame.setVisible(true);
    			 frame.setLayout(new FlowLayout());
    			 frame.add(savefield);
    			 frame.add(save);
    			 frame.setSize(400,75);
    			 
    		 }catch(Exception x){
    			 x.printStackTrace();
    		 }
    		
    	}
    	
    }
    class quick1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		nouns.add(nounbox1.getText());
    		nouns.add(nounbox2.getText());
    		nouns.add(nounbox3.getText());
    		adjectives.add(adjbox1.getText());
    		adjectives.add(adjbox2.getText());
    		adjectives.add(adjbox3.getText());
    		verbs.add(verbbox1.getText());
    		verbs.add(verbbox2.getText());
    		verbs.add(verbbox3.getText());
    		
    		String[] nounarray = nouns.toArray(new String[nouns.size()]);
    		String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    		String[] verbarray = verbs.toArray(new String[verbs.size()]);
    		
    		int countnoun = nounarray.length;
    		int countadj = adjarray.length;
    		int countverb = verbarray.length;
    		
    		int ran1 = (int) (Math.random() * countverb);
    		int ran2 = (int) (Math.random() * countadj);
    		int ran3 = (int) (Math.random() * countnoun);
    		
    		 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    		 String funny2 = nounarray [ran3]+ " " +adjarray [ran2]+ " " + verbarray [ran1]+" ";
    		 String funny3 = adjarray [ran2]+ " " + verbarray [ran1]+" "+ nounarray [ran3]+" ";
    		 String funny4 = verbarray[ran1] + " " + adjarray[ran2] + " " + nounarray[ran3]+" ";
    		
    		JFrame frame = new JFrame("Arrangements");
    	String[] aras = {"ANV", "NAV", "AVN", "VAN"};
    	
    	HashMap<String, String> map = new HashMap<String, String>();
    	
    	map.put("ANV", funny1);
    	map.put("NAV", funny2);
    	map.put("NAV", funny3);
    	map.put("VAN", funny4);
    	
    	list = new JList(map);
    	list.setSelectedIndex(0);
    	list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    	list.addListSelectionListener(new listListener());
    	JButton set = new JButton("Done");
    	set.addActionListener(new setListener());
    	frame.getContentPane().add(BorderLayout.CENTER, list);
    	frame.getContentPane().add(BorderLayout.SOUTH, set);
    	frame.setSize(250,250);
    	frame.setVisible(true);
    		
    	}
    	
    }
    class quick2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class quick3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class nounbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class nounbox3listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	}
    class adjbox1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class adjbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class adjbox3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class verbbox1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class verbbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class verbbox3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class midguiListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class savebuttonListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		try{
    			String fileName = savefield.getText();
    		FileWriter writer = new FileWriter(fileName);
    		 writer.write(midgui.getText());
    		 writer.close();
    		 
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
    		
    	}
    	
    }
    public void establishConnection(){
    	try{
    	Socket sock = new Socket("192.168.0.195", 5620);
    	
    	}catch(Exception ex){
    		midgui.append("Couldn't get connection");
    	}
    }
    public void setPhraseAra(){
    	String[] nounarray = nouns.toArray(new String[nouns.size()]);
    	String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    	String[] verbarray = verbs.toArray(new String[verbs.size()]);
    	
    	int countnoun = nounarray.length;
    	int countadj = adjarray.length;
    	int countverb = verbarray.length;
    	
    	int ran1 = (int) (Math.random() * countverb);
    	int ran2 = (int) (Math.random() * countadj);
    	int ran3 = (int) (Math.random() * countnoun);
    	
    	 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny2 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny3 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	
    	p = a;
    	a = funny2;
    		
    }
    public void getPhraseAra(){
    	
    	
    	nouns.add(nounbox1.getText());
    	nouns.add(nounbox2.getText());
    	nouns.add(nounbox3.getText());
    	adjectives.add(adjbox1.getText());
    	adjectives.add(adjbox2.getText());
    	adjectives.add(adjbox3.getText());
    	verbs.add(verbbox1.getText());
    	verbs.add(verbbox2.getText());
    	verbs.add(verbbox3.getText());
    	
    	String[] nounarray = nouns.toArray(new String[nouns.size()]);
    	String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    	String[] verbarray = verbs.toArray(new String[verbs.size()]);
    	
    	int countnoun = nounarray.length;
    	int countadj = adjarray.length;
    	int countverb = verbarray.length;
    	
    	int ran1 = (int) (Math.random() * countverb);
    	int ran2 = (int) (Math.random() * countadj);
    	int ran3 = (int) (Math.random() * countnoun);
    	
    	 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny2 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny3 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 
    	 midgui.setText(p + "/n");
    }
    class setListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class listListener implements ListSelectionListener{
    
    	public void valueChanged(ListSelectionEvent e) {
    		if(!e.getValueIsAdjusting()){
    			
    			String selection = (String) list.getSelectedValue();
    			p = selection;
    		}else{
    			
    		}
    		
    	}
    	
    }
    }
    Error:

    Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
    The constructor JList(HashMap<String,String>) is undefined

    at Phrasebot$quick1Listener.actionPerformed(Phrasebot.java:345)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1882)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2202)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:5602)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
    at java.awt.Component.processEvent(Component.java:5367)
    at java.awt.Container.processEvent(Container.java:2010)
    at java.awt.Component.dispatchEventImpl(Component.java:4068)
    at java.awt.Container.dispatchEventImpl(Container.java:2068)
    at java.awt.Component.dispatchEvent(Component.java:3903)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3936)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
    at java.awt.Container.dispatchEventImpl(Container.java:2054)
    at java.awt.Window.dispatchEventImpl(Window.java:1801)
    at java.awt.Component.dispatchEvent(Component.java:3903)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

  5. #5
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Jlist help

    You won't get anywhere unless you read the API docs for the classes you want to use, and preferably the Java Tutorial details on how to use them, before writing the code.

    The solution I generally use is to make a class that contains the display string for the list and the associated value (a key to a map, or the actual value you need). Create objects of this class containing the display text and the value and put them into the list model. This way, the list model itself is the map. When and item is selected in the list, you can get the object at that index and pull out the value from it, e.g.
    Code:
    class ListItem {
        String displayText;
        MyValue value;
    
        ListItem(String displayText, MyValue  value) {
            this.displayText = displayText;
            this.value = value;
        }
    
        public MyValue getValue() {
            return value;
        }
    
        // the JList uses toString for its display
        public String toString() {
            return displayText;
        }
    }
    ...
    final JList list = new JList();
    DefaultListModel dlm = new DefaultListModel();
    
    for (int i=0; i<10; i++) {
        // add a new ListItem containing display text and a new value
        dlm.addElement(new ListItem(("Item "+i), new MyValue(i)));
    }
    list.setModel(dlm);
    
    list.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
    
                // get the selected item
                ListItem item = (ListItem) list.getSelectedValue();
    
                // get the value from the item and print it
                MyValue value = item.getValue();
                System.out.println("value = " + value);
            }
        }
    });
    In fact, to save future effort, you can create a generic ListItem class for your library:
    Code:
    class ListItem<T> {
        String displayText;
        T value;
    
        ListItem(String displayText, T value) {
            this.displayText = displayText;
            this.value = value;
        }
    
        public T getValue() {
            return value;
        }
    
        public String toString() {
            return displayText;
        }
    }
    It is a bad plan that admits of no modification...
    P. Syrus
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  6. #6
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Question Re: Jlist help

    How would this work since MyValue isn't defined?

  7. #7
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Jlist help

    Quote Originally Posted by Shaken_Earth View Post
    How would this work since MyValue isn't defined?
    it's just an example. 'MyValue' can be whatever you want to use for the value - a String, Component, a Double, your own class, whatever makes your life easy - that's why I gave you the generic version that you can use with different types for different Lists.

    When example code is posted up on a forum, it's generally intended for you to study and try to understand so that you can adapt it for your own use. Some posters even put deliberate simple mistakes into the code they post so that it can't be just copied and pasted without some attempt to understand it. Most of us want to help people understand their problems, not just write their code for them - we can get paid for doing that

    Good teaching is more a giving of the right questions than a giving of the right answers...
    J. Albers
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  8. #8
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    O okay thanks

  9. #9
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    So I've been trying to make this thing work and it's giving me an error like this:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Phrasebot$listListener.valueChanged(Phrasebot.java:611)
    at javax.swing.JList.fireSelectionValueChanged(JList.java:1317)
    at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1331)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:157)
    at javax.swing.DefaultListSelectionModel.setValueIsAdjusting(DefaultListSelectionModel.java:619)
    at javax.swing.JList.setValueIsAdjusting(JList.java:1671)
    at javax.swing.plaf.basic.BasicListUI$Handler.mouseReleased(BasicListUI.java:2371)
    at javax.swing.plaf.basic.BasicListUI$MouseInputHandler.mouseReleased(BasicListUI.java:1320)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
    at java.awt.Component.processMouseEvent(Component.java:5602)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
    at java.awt.Component.processEvent(Component.java:5367)
    at java.awt.Container.processEvent(Container.java:2010)
    at java.awt.Component.dispatchEventImpl(Component.java:4068)
    at java.awt.Container.dispatchEventImpl(Container.java:2068)
    at java.awt.Component.dispatchEvent(Component.java:3903)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3936)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
    at java.awt.Container.dispatchEventImpl(Container.java:2054)
    at java.awt.Window.dispatchEventImpl(Window.java:1801)
    at java.awt.Component.dispatchEvent(Component.java:3903)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

    It says it's on line 611 but I don't understand why it's giving me the error. Does ListItem have to implement something? It was working fine with String. and others. Or does it have to do with ListItem having a key AND a value? Please Help!

    Code in next post.

  10. #10
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    Phrasebot Class:

    Code:
    //Phrasebot is property of shakenearth.com
    //Code by Thomas Lisankie
    //You may not use any of this code
    //you may not distribute this program either
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    
    import java.io.*;
    import java.net.*;
    public class Phrasebot implements ActionListener {
    	
    	JTextArea midgui;
    	JButton phrasemaker;
    	Box boxleft;
    	
    	JTextField nounbox1;
    	JTextField nounbox2;
    	JTextField nounbox3;
    	
    	JTextField adjbox1;
    	JTextField adjbox2;
    	JTextField adjbox3;
    	
    	JTextField verbbox1;
    	JTextField verbbox2;
    	JTextField verbbox3;
    	
    	HashSet<String> nouns = new HashSet<String>();
    	HashSet<String> adjectives = new HashSet<String>();
    	HashSet<String> verbs = new HashSet<String>();
    	
    	JList list;
    
    	String a;
    	
    	JTextField savefield;
    	JButton save;
    	
    	
    	
    	String p;
    	
    	ListItem item1;
    	ListItem item2;
    	ListItem item3;
    	ListItem item4;
    	
    	
    public static void main(String[] args){
    try{
    	
    	Phrasebot bot = new Phrasebot();
    bot.go();
    }catch(Error Ex){
    	Ex.printStackTrace();
    }
    }
    public void go() {
    	
    	
    	JPanel pcenter = new JPanel();
    	JFrame frame = new JFrame("Phrasebot");//makes a new JFrame called "Phrasebot"
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//sets the default close operation to EXIT_ON_CLOSE
    	boxleft = new Box(BoxLayout.Y_AXIS);
    	Box boxright = new Box(BoxLayout.Y_AXIS);
    	
    	Font midfont = new Font("Comic Sans MS", Font.BOLD, 18);
    	
    	JPanel bigpanel = new JPanel();//makes a new JPanel called bigpanel
    	bigpanel.setLayout(new BoxLayout(bigpanel,BoxLayout.Y_AXIS));//sets bigpanel's default layout to BoxLayout
    	JPanel spacer = new JPanel();//makes a new JPanel called spacer
    	spacer.setLayout(new BoxLayout(spacer, BoxLayout.Y_AXIS));//sets spacer's layout to BoxLayout
    	JLabel label = new JLabel(" ");//makes a new JLabel
    	spacer.add(label);//adds label to spacer
    	bigpanel.add(spacer);//adds spacer to bigpanel
    	JPanel peast = new JPanel();//makes a new panel called peast
    	bigpanel.add(peast);//bigpanel adds peast
    	peast.setLayout(new  BoxLayout(peast,BoxLayout.Y_AXIS));//sets peast's layout to boxlayout
    	JButton morenoun = new JButton("Add a Noun");//makes a new button called more noun with the text "More Nouns"
    	morenoun.addActionListener(new morenounListener());//morenoun adds an actionlistener which is a morenounlistener()
    	morenoun.setFont(midfont);
    	peast.add(morenoun);//peast adds morenoun
    	boxright.add(morenoun);
    	JButton clearnoun = new JButton("Clear Nouns");//makes a new button called clearnoun with the text "Clear Nouns"
    	clearnoun.addActionListener(new clearnounListener());//clearnoun adds an actionlistener which is a clearnounlistener()
    	clearnoun.setFont(midfont);
    	peast.add(clearnoun);//peast adds clearnoun
    	boxright.add(clearnoun);
    	JLabel spacer2 = new JLabel(" ");//makes a new label called spacer2
    	peast.add(spacer2);//peast adds spacer2
    	boxright.add(spacer2);
    	JButton moreadj = new JButton("Add an Adjective");//makes a new button called moreadj with the text "More Adjectives"
    	moreadj.addActionListener(new moreadjListener());//moreadj adds an actionlistener which is a moreadjlistener()
    	moreadj.setFont(midfont);
    	peast.add(moreadj);//peast adds moreadj
    	boxright.add(moreadj);
    	JButton clearadj = new JButton("Clear Adjectives");//makes a new button called clearadj with the text "Cear Adjectives"
    	clearadj.addActionListener(new clearadjListener());//clearadj adds an actionlistener which is a clearadjlistener()
    	clearadj.setFont(midfont);
    	peast.add(clearadj);//peast adds clearadj
    	boxright.add(clearadj);
    	JLabel spacer3 = new JLabel(" ");//makes a new label called spacer3
    	peast.add(spacer3);//peast adds
    	boxright.add(spacer3);
    	JButton moreverb = new JButton("Add a Verb");//makes a new button called moreverb with the text "More Verbs"
    	moreverb.addActionListener(new moreverbListener());//moreverb adds an actionlistener which is a moreverblistener()
    	moreverb.setFont(midfont);
    	peast.add(moreverb);//peast adds moreverb
    	boxright.add(moreverb);
    	JButton clearverb = new JButton("Clear Verbs");//makes a new button called clearverb with the text "Clear Verbs"
    	clearverb.addActionListener(new clearverbListener());//clearverb adds an actionlistener which is a clearverbListener()
    	clearverb.setFont(midfont);
    	peast.add(clearverb);//peast adds clearverb
    	boxright.add(clearverb);
    	JLabel savespacer = new JLabel(" ");//makes a new label called savespacer
    	peast.add(savespacer);//peast adds savespacer
    	boxright.add(savespacer);
    	JButton savewords = new JButton("Save Set");//makes a new button called save words
    	savewords.addActionListener(new savewordsListener());//savewords adds an actionlistener which is a savewordsListener()
    	savewords.setFont(midfont);
    	peast.add(savewords);//peast adds savewords
    	boxright.add(savewords);
    	JButton savesession = new JButton("Save Phrase");//creates a new button called savesession with the text "Save Phrases"
    	savesession.addActionListener(new savesessionListener());//savesession adds an actionlistener which is a savesessionListener()
    	savesession.setFont(midfont);
    	peast.add(savesession);//peast adds savesession
    	boxright.add(savesession);
    	JLabel quickspacer = new JLabel(" ");//makes a new label called quickspacer
    	peast.add(quickspacer);//peast adds quickspacer
    	JButton quick1 = new JButton("Arrangements");//makes a new button called quick1 with the text "Quickie Button 1"
    	quick1.addActionListener(new quick1Listener());//
    	quick1.setFont(midfont);
    	peast.add(quick1);
    	boxright.add(quick1);
    	
    	
    	JPanel pwest = new JPanel();
    	pwest.setLayout(new BoxLayout(pwest,BoxLayout.Y_AXIS));
    	JPanel bigpanel2 = new JPanel();
    	bigpanel2.add(pwest);
    	
    	midgui = new JTextArea(10,20);
    	midgui.setEditable(false);
    	midgui.setLineWrap(true);
    	midgui.setFont(midfont);
    	JScrollPane scroll = new JScrollPane(midgui);
    	scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    	scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    	pcenter.add(scroll);
    	
    	
    	
    	
    	nounbox1 = new JTextField("Noun	");
    	nounbox2 = new JTextField("Noun	");
    	nounbox3 = new JTextField("Noun	");
    	nounbox1.setFont(midfont);
    	nounbox2.setFont(midfont);
    	nounbox3.setFont(midfont);
    	JLabel spacer4 = new JLabel(" ");
    	pwest.add(nounbox1);
    	nounbox1.addActionListener(this);
    	pwest.add(nounbox2);
    	nounbox2.addActionListener(new nounbox2Listener());
    	pwest.add(nounbox3);
    	nounbox3.addActionListener(new nounbox3listener());
    	pwest.add(spacer4);
    	adjbox1 = new JTextField("Adjective  ");
    	adjbox2 = new JTextField("Adjective  ");
    	adjbox3 = new JTextField("Adjective  ");
    	adjbox1.setFont(midfont);
    	adjbox2.setFont(midfont);
    	adjbox3.setFont(midfont);
    	JLabel spacer5 = new JLabel(" ");
    	pwest.add(adjbox1);
    	adjbox1.addActionListener(new adjbox1Listener());
    	pwest.add(adjbox2);
    	adjbox2.addActionListener(new adjbox2Listener());
    	pwest.add(adjbox3);
    	adjbox3.addActionListener(new adjbox3Listener());
    	pwest.add(spacer5);
    	verbbox1 = new JTextField("Verb  ");
    	verbbox2 = new JTextField("Verb  ");
    	verbbox3 = new JTextField("Verb  ");
    	verbbox1.setFont(midfont);
    	verbbox2.setFont(midfont);
    	verbbox3.setFont(midfont);
    	pwest.add(verbbox1);
    	verbbox1.addActionListener(new verbbox1Listener());
    	pwest.add(verbbox2);
    	verbbox2.addActionListener(new verbbox2Listener());
    	pwest.add(verbbox3);
    	verbbox3.addActionListener(new verbbox3Listener());
    	JPanel psouth = new JPanel();
    	JPanel bigpanel3 = new JPanel();
    	bigpanel3.add(psouth);
    	phrasemaker = new JButton("Make A Phrase!");
    	phrasemaker.addActionListener(new phrasemakerListener());
    	phrasemaker.setFont(midfont);
    	psouth.add(phrasemaker);
    	boxleft.add(nounbox1);
    	boxleft.add(nounbox2);
    	boxleft.add(nounbox3);
    	Box.createVerticalGlue();
    	boxleft.add(adjbox1);
    	boxleft.add(adjbox2);
    	boxleft.add(adjbox3);
    Box.createVerticalGlue();
    	boxleft.add(verbbox1);
    	boxleft.add(verbbox2);
    	boxleft.add(verbbox3);
    	frame.setSize(875,600);//sets the size of the JFrame
    	frame.setVisible(true);//sets the ability to see the JFrame
    	
    	
    	frame.getContentPane().add(BorderLayout.EAST, boxright);
    	frame.getContentPane().add(BorderLayout.WEST, boxleft);
    	frame.getContentPane().add(BorderLayout.SOUTH, bigpanel3);
    	frame.getContentPane().add(BorderLayout.CENTER, scroll);
    
    }
    public void actionPerformed(ActionEvent e) {
    	
    	
    }
    class phrasemakerListener implements ActionListener{
    	public void actionPerformed(ActionEvent ev) {
    		try{	
    			nouns.add(nounbox1.getText());
    			nouns.add(nounbox2.getText());
    			nouns.add(nounbox3.getText());
    			adjectives.add(adjbox1.getText());
    			adjectives.add(adjbox2.getText());
    			adjectives.add(adjbox3.getText());
    			verbs.add(verbbox1.getText());
    			verbs.add(verbbox2.getText());
    			verbs.add(verbbox3.getText());
    			
    			String[] nounarray = nouns.toArray(new String[nouns.size()]);
    			String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    			String[] verbarray = verbs.toArray(new String[verbs.size()]);
    			
    			int countnoun = nounarray.length;
    			int countadj = adjarray.length;
    			int countverb = verbarray.length;
    			
    			int ran1 = (int) (Math.random() * countverb);
    			int ran2 = (int) (Math.random() * countadj);
    			int ran3 = (int) (Math.random() * countnoun);
    			
    			 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    			 String funny2 = nounarray [ran3]+ " " +adjarray [ran2]+ " " + verbarray [ran1]+" ";
    			 String funny3 = adjarray [ran2]+ " " + verbarray [ran1]+" "+ nounarray [ran3]+" ";
    			 String funny4 = verbarray[ran1] + " " + adjarray[ran2] + " " + nounarray[ran3]+" ";
    			
    			p = funny1;
    		midgui.append(p + "\n ");
    		phrasemaker.setText("Make Another!");
    		}
    		catch(Exception ex){
    		ex.printStackTrace();	
    		}
    	}
    	
    }
    
    class morenounListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		nouns.add(nounbox1.getText());
    		nounbox1.setText("");
    		
    	}
    	
    }
    class clearnounListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		nouns.clear();
    		
    	}
    	
    }
    class moreadjListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		adjectives.add(adjbox1.getText());
    		adjbox1.setText("");
    		
    	}
    	
    }
    class clearadjListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 adjectives.clear();
    		
    	}
    	
    }
    class moreverbListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		verbs.add(verbbox1.getText());
    		verbbox1.setText(""); 
    		
    	}
    	
    }
    class clearverbListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 verbs.clear();
    		
    	}
    	
    }
    class savewordsListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		try{
    			FileOutputStream fileout = new FileOutputStream("words.pb");
    		ObjectOutputStream out = new ObjectOutputStream(fileout);
    		
    		out.writeObject(nouns);
    		out.close();
    		midgui.append("words saved");
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
    	}
    	
    }
    class savesessionListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 try{
    			 JFrame frame = new JFrame();
    			 savefield = new JTextField("Untitled.txt");
    			 JButton save = new JButton("Save");
    			 save.addActionListener(new savebuttonListener());
    			 frame.setVisible(true);
    			 frame.setLayout(new FlowLayout());
    			 frame.add(savefield);
    			 frame.add(save);
    			 frame.setSize(400,75);
    			 
    		 }catch(Exception x){
    			 x.printStackTrace();
    		 }
    		
    	}
    	
    }
    class quick1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		nouns.add(nounbox1.getText());
    		nouns.add(nounbox2.getText());
    		nouns.add(nounbox3.getText());
    		adjectives.add(adjbox1.getText());
    		adjectives.add(adjbox2.getText());
    		adjectives.add(adjbox3.getText());
    		verbs.add(verbbox1.getText());
    		verbs.add(verbbox2.getText());
    		verbs.add(verbbox3.getText());
    		
    		String[] nounarray = nouns.toArray(new String[nouns.size()]);
    		String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    		String[] verbarray = verbs.toArray(new String[verbs.size()]);
    		
    		int countnoun = nounarray.length;
    		int countadj = adjarray.length;
    		int countverb = verbarray.length;
    		
    		int ran1 = (int) (Math.random() * countverb);
    		int ran2 = (int) (Math.random() * countadj);
    		int ran3 = (int) (Math.random() * countnoun);
    		
    		 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    		 String funny2 = nounarray [ran3]+ " " +adjarray [ran2]+ " " + verbarray [ran1]+" ";
    		 String funny3 = adjarray [ran2]+ " " + verbarray [ran1]+" "+ nounarray [ran3]+" ";
    		 String funny4 = verbarray[ran1] + " " + adjarray[ran2] + " " + nounarray[ran3]+" ";
    		
    		JFrame frame = new JFrame("Arrangements");
    	String[] aras = {"ANV", "NAV", "AVN", "VAN"};
    	
    	final JList list = new JList();
    	DefaultListModel dlm = new DefaultListModel();
    
    		item1 = new ListItem("ANV", funny1);
    	    item2 = new ListItem("NAV", funny2);
    	    item3 = new ListItem("AVN", funny3);
    	    item4 = new ListItem("VAN", funny4);
    	
    	for(int i = 0; i<1; i++){
    	    // add a new ListItem containing display text and a new value
    	    dlm.addElement(item1.getKey());
    	    dlm.addElement(item2.getKey());
    	    dlm.addElement(item3.getKey());
    	    dlm.addElement(item4.getKey());
    	}
    	    
    	list.setModel(dlm);
    	
    	
    	
    	
    	list.setSelectedIndex(0);
    	list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    	list.addListSelectionListener(new listListener());
    	JButton set = new JButton("Done");
    	set.addActionListener(new setListener());
    	frame.getContentPane().add(BorderLayout.CENTER, list);
    	frame.getContentPane().add(BorderLayout.SOUTH, set);
    	frame.setSize(250,250);
    	frame.setVisible(true);
    		
    	}
    	
    }
    class quick2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class quick3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class nounbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class nounbox3listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	}
    class adjbox1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class adjbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class adjbox3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class verbbox1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class verbbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class verbbox3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class midguiListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class savebuttonListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		try{
    			String fileName = savefield.getText();
    		FileWriter writer = new FileWriter(fileName);
    		 writer.write(midgui.getText());
    		 writer.close();
    		 
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
    		
    	}
    	
    }
    public void establishConnection(){
    	try{
    	Socket sock = new Socket("192.168.0.195", 5620);
    	
    	}catch(Exception ex){
    		midgui.append("Couldn't get connection");
    	}
    }
    public void setPhraseAra(){
    	String[] nounarray = nouns.toArray(new String[nouns.size()]);
    	String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    	String[] verbarray = verbs.toArray(new String[verbs.size()]);
    	
    	int countnoun = nounarray.length;
    	int countadj = adjarray.length;
    	int countverb = verbarray.length;
    	
    	int ran1 = (int) (Math.random() * countverb);
    	int ran2 = (int) (Math.random() * countadj);
    	int ran3 = (int) (Math.random() * countnoun);
    	
    	 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny2 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny3 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	
    	p = a;
    	a = funny2;
    		
    }
    public void getPhraseAra(){
    	
    	
    	nouns.add(nounbox1.getText());
    	nouns.add(nounbox2.getText());
    	nouns.add(nounbox3.getText());
    	adjectives.add(adjbox1.getText());
    	adjectives.add(adjbox2.getText());
    	adjectives.add(adjbox3.getText());
    	verbs.add(verbbox1.getText());
    	verbs.add(verbbox2.getText());
    	verbs.add(verbbox3.getText());
    	
    	String[] nounarray = nouns.toArray(new String[nouns.size()]);
    	String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    	String[] verbarray = verbs.toArray(new String[verbs.size()]);
    	
    	int countnoun = nounarray.length;
    	int countadj = adjarray.length;
    	int countverb = verbarray.length;
    	
    	int ran1 = (int) (Math.random() * countverb);
    	int ran2 = (int) (Math.random() * countadj);
    	int ran3 = (int) (Math.random() * countnoun);
    	
    	 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny2 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny3 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 
    	 midgui.setText(p + "/n");
    }
    class setListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class listListener implements ListSelectionListener{
    
    	public void valueChanged(ListSelectionEvent e) {
    		if(!e.getValueIsAdjusting()){
    			
    			// get the selected item
               ListItem item = (ListItem) list.getSelectedValue();
    
                // get the value from the item and print it
               
    			p = item.getValue();
    		}else{
    			System.out.println("It prevented it =)!");
    		}
    		
    	}
    	
    }
    }
    ListItem class:

    Code:
    
    public class ListItem {
        String displayText;
        String value;
    
        public ListItem(String displayText,  String value) {
            this.displayText = displayText;
            this.value = value;
        }
    
        public String getValue() {
            return value;
        }
    
        public String getKey() {
            return displayText;
        }
    }

  11. #11
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    By the way line 611 is the line that reads ListItem item = (ListItem) list.getSelectedValue();

  12. #12
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Jlist help

    The 'list' variable that the error line tries to use is null - that's what a NullPointerException means. It's a member variable of Phrasebot and it never gets initialized.

    There is a 'list' variable created and initialized in the actionPerformed() method of quickListener, but it's a method-local variable and isn't visible anywhere else.

    I'm guessing you wanted to initialize the Phrasebot member variable instead of creating a method-local variable...

    I detect a hint of deja-vu about this bug

    As a general rule, the class constructor should prevent this kind of thing by making sure that all relevant variables are initialized. The constructor's job is to get the object into a usable state or die trying. 'Usable' in this context means stable - you should be able to call any of the public methods without it falling over in a heap.

    Act in haste and repent at leisure; code too soon and debug forever...
    R. Kennington
    Last edited by dlorde; July 4th, 2009 at 01:54 PM.
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  13. #13
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    Yes I feel the deja-vu as well . The bad thing about me is when I see the bug and find the line the bug is on I never bother to look out of the method the line is invoked on. I need to change that :P . Anyway, I changed the variable but now it's giving me a ClassCastException. I just read in the Java API about ClassCastException and it says:

    "Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

    Object x = new Integer(0);
    System.out.println((String)x);"

    I'm not sure what they mean by this. If someone could explain what they mean by this it would be greatly appreciated. Also, if you can find out why it's giving me this exception that would be great. By the error is on the same line as before. Here's the error:


    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String
    at Phrasebot$listListener.valueChanged(Phrasebot.java:619)
    at javax.swing.JList.fireSelectionValueChanged(JList.java:1317)
    at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1331)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:157)
    at javax.swing.DefaultListSelectionModel.setValueIsAdjusting(DefaultListSelectionModel.java:619)
    at javax.swing.JList.setValueIsAdjusting(JList.java:1671)
    at javax.swing.plaf.basic.BasicListUI$Handler.mouseReleased(BasicListUI.java:2371)
    at javax.swing.plaf.basic.BasicListUI$MouseInputHandler.mouseReleased(BasicListUI.java:1320)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
    at java.awt.Component.processMouseEvent(Component.java:5602)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
    at java.awt.Component.processEvent(Component.java:5367)
    at java.awt.Container.processEvent(Container.java:2010)
    at java.awt.Component.dispatchEventImpl(Component.java:4068)
    at java.awt.Container.dispatchEventImpl(Container.java:2068)
    at java.awt.Component.dispatchEvent(Component.java:3903)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3936)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
    at java.awt.Container.dispatchEventImpl(Container.java:2054)
    at java.awt.Window.dispatchEventImpl(Window.java:1801)
    at java.awt.Component.dispatchEvent(Component.java:3903)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

  14. #14
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Jlist help

    A ClassCastException means you're trying to cast to the wrong class type. Old-style containers in Java can only store Objects, so when you pull an object out, you need to cast it to the type you originally put in. If you try to cast to the wrong type, you'll get an exception.

    The error message is telling you than on line 619 of Phrasebot.java, in the valueChanged method, you're trying to cast something to the wrong type. If it's an object you got out of a list, it isn't what you're trying to cast it to.

    Like I said before, unless you work everything out in advance before writing any code, you'll spend more time trying to fix it than you would have done working it out in advance - and in the end it will probably be worse. Writing legal Java is hard enough when you're starting out, without also having to tweak your design as you go. It's sometimes quicker to start again with new knowledge and experience than to try to fix the bugs a mass of code that isn't quite right.

    Plan to throw one away; you will anyhow...
    F. Brooks
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  15. #15
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: Jlist help

    Thanks for the advice. I'll keep it in mind for future projects because this project is very close to being done. Could you please tell me how to fix the problem?

Page 1 of 2 12 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center