• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JComboBox

 
Steven Coddington
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know how to get information from JCombo box: This class does the GUI

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

public class PersonListGUI extends JFrame implements ItemListener
{
// instance variables
private String name[]={"Fred", "Bill", "Ethel"};
private JComboBox nameList = null;
private JFrame frame = null;
//private DescriptionPanel dp = new DescriptionPanel();
/**
* Constructor for objects of class PersonListGUI
*/
public PersonListGUI()
{
frame = new JFrame();
frame.setTitle("A List of Salespeople");
nameList = new JComboBox(name);
frame.getContentPane().add(nameList);
frame.setSize(300,70);
frame.setVisible(true);
System.out.println("hello");
}
public void actionPerformed(){
System.out.println("action performed");
}
public void itemStateChanged(ItemEvent e){
if (e.getSource() instanceof JComboBox){
String s = (String)e.getItem();
int k = nameList.getSelectedIndex();
System.out.println("k = " + k);
}
}
public int indexReturner(){
int k = nameList.getSelectedIndex();
return k;
}
}

It works fine. The box is displayed and I can change the display. This class is meant to make an instance of the box and get the returned data.

import javax.swing.*;
import java.awt.event.*;
public class Tester
{

public void Tester()
{
PersonListGUI pl = new PersonListGUI();
int k = pl.indexReturner();
System.out.println (k);
return ;
}
}


It works fine on the first pass. I get the index after the GUI is created (0), but how do I get information after each change to the selected item. It must have something to do with the listener that I am not implementing.

Thanks
 
Gregg Bolinger
GenRocket Founder
Ranch Hand
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to the Swing forum.
 
Gregg Bolinger
GenRocket Founder
Ranch Hand
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


You've got this working. But you aren't doing anything outside of the if's scope with the selectedIndex other than printing it out.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe there methods getSelectedItem and getSelectedIndex that you can call on a JComboBox
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic