1

如何从 JComboBox 中获得与多个数组选择相关的选择?

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

class ContactsReader extends JFrame
{
public JPanel mainPanel;
public JPanel buttonPanel;
public JPanel displayPanel;

public JLabel titleLabel;
public JLabel nameLabel;
public JLabel ageLabel;
public JLabel emailLabel;
public JLabel cellPhoneLabel;
public JLabel comboBoxLabel;

public JButton exitButton;

public JTextField nameTextField;
public JTextField ageTextField;
public JTextField emailTextField;
public JTextField cellPhoneTextField;

public JComboBox<String> contactBox;

public String[] getContactNames;
public String[] displayContactNames;

public File contactFile;
public Scanner inputFile;

public String selection;

public ContactsReader()
{
    super("Contacts Reader");
    setSize(400,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());

    buildPanel();

    add(mainPanel, BorderLayout.CENTER);

    pack();
    setVisible(true);

} 

public void buildPanel()
{
    titleLabel = new JLabel("Please enter contact information");
    mainPanel = new JPanel(new BorderLayout());

    buttonPanel();
    displayPanel();

    mainPanel.add(titleLabel, BorderLayout.NORTH);
    mainPanel.add(buttonPanel, BorderLayout.SOUTH);
    mainPanel.add(displayPanel, BorderLayout.CENTER);
}

public void buttonPanel()
{
    //create submit and exit buttons
    exitButton = new JButton("Exit");
    exitButton.addActionListener(new exitButtonListener());

    buttonPanel = new JPanel(); //create button panel

    buttonPanel.add(exitButton);    //add exit button to panel
}

public void displayPanel()
{
    String nameHolder;

    int count = 0;

    nameLabel = new JLabel("Name");
    ageLabel = new JLabel("Age)");
    emailLabel = new JLabel("Email");
    cellPhoneLabel = new JLabel("Cell Phone #");
    comboBoxLabel = new JLabel("Select a Conact");

    nameTextField = new JTextField(10);
    nameTextField.setEditable(false);
    ageTextField = new JTextField(10);
    ageTextField.setEditable(false);
    emailTextField = new JTextField(10);
    emailTextField.setEditable(false);
    cellPhoneTextField = new JTextField(10);
    cellPhoneTextField.setEditable(false);

    try{
        contactFile = new File("ContactData.txt");
        inputFile = new Scanner(contactFile);   
    }
    catch (Exception event){}

    while (inputFile.hasNext())
    {
        nameHolder = inputFile.nextLine();
        count++;
    }
    inputFile.close();

    String getContactNames[] = new String[count];
    String displayContactNames[] = new String[count/4];

    try{
        contactFile = new File("ContactData.txt");
        inputFile = new Scanner(contactFile);   
    }
    catch (Exception event){}

    for (int i = 0; i < count; i++)
    {
        if (inputFile.hasNext())
        {
            nameHolder = inputFile.nextLine();
            getContactNames[i] = nameHolder;

            if (i % 4 == 0)
            {
                displayContactNames[i/4] = getContactNames[i];
            }

        }
    }

    inputFile.close();

    contactBox = new JComboBox<String>(displayContactNames);
    contactBox.setEditable(false);
    contactBox.addActionListener(new contactBoxListener());

    displayPanel = new JPanel(new GridLayout(10,1));

    displayPanel.add(comboBoxLabel);
    displayPanel.add(contactBox);
    displayPanel.add(nameLabel);
    displayPanel.add(nameTextField);
    displayPanel.add(ageLabel);
    displayPanel.add(ageTextField);
    displayPanel.add(emailLabel);
    displayPanel.add(emailTextField);
    displayPanel.add(cellPhoneLabel);
    displayPanel.add(cellPhoneTextField);

}       

private class exitButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        System.exit(0); //set exit button to exit even when pressed
    }
}

private class contactBoxListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //get selection from dropdown menu
        selection = (String) contactBox.getSelectedItem();
    }
}

public static void main(String[] args)
{

    new ContactsReader();   //create instance of Contact Reader
}

}

我希望选择将姓名、年龄、电子邮件和手机号码发送到相应的文本字段。我可以找到一个选择,但不知道如何让它选择正确的数组选择并将其发送到文本字段。

4

1 回答 1

4

不要让 JComboBox 只保存字符串,而是让它保存自定义类的对象,这些对象包含您在选择它时需要的所有信息。然后使用选定的对象来填充您的 JTextField。

例如,考虑创建一个名为 Contact 的类,

public class MyContact {
  String name;
  Date dateOfBirth; // in place of age
  String email;
  String cellPhone;

  //...
}

然后创建一个JComboBox<MyContact>

当一个项目被选中时,调用相应的getXXX()getter方法来提取信息来填充JTextField。您将希望为 JComboBox 提供一个自定义 CellRenderer,以便它可以很好地显示联系人。

例如:

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

public class MyComboEg extends JPanel {
   private static final MyData[] data = {
         new MyData("Monday", 1, false),
         new MyData("Tuesday", 2, false),
         new MyData("Wednesday", 3, false),
         new MyData("Thursday", 4, false),
         new MyData("Friday", 5, false),
         new MyData("Saturday", 6, true),
         new MyData("Sunday", 7, true),
   };   
   private JComboBox<MyData> myCombo = new JComboBox<MyData>(data);
   private JTextField textField = new JTextField(10);
   private JTextField valueField = new JTextField(10);
   private JTextField weekendField = new JTextField(10);

   public MyComboEg() {
      add(myCombo);
      add(new JLabel("text:"));
      add(textField);
      add(new JLabel("value:"));
      add(valueField);
      add(new JLabel("weekend:"));
      add(weekendField);

      myCombo.setRenderer(new DefaultListCellRenderer(){
         @Override
         public Component getListCellRendererComponent(JList list,
               Object value, int index, boolean isSelected, boolean cellHasFocus) {
            String text = value == null ? "" : ((MyData)value).getText();
            return super.getListCellRendererComponent(list, text, index, isSelected,
                  cellHasFocus);
         }
      });
      myCombo.setSelectedIndex(-1);

      myCombo.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            // MyData myData = (MyData) myCombo.getSelectedItem();
            MyData myData = myCombo.getSelectedItem();
            textField.setText(myData.getText());
            valueField.setText(String.valueOf(myData.getValue()));
            weekendField.setText(String.valueOf(myData.isWeekend()));
         }
      });
   }

   private static void createAndShowGui() {
      MyComboEg mainPanel = new MyComboEg();

      JFrame frame = new JFrame("MyComboEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class MyData {
   private String text;
   private int value;
   private boolean weekend;

   MyData(String text, int value, boolean weekend) {
      this.text = text;
      this.value = value;
      this.weekend = weekend;
   }
   public String getText() {
      return text;
   }
   public int getValue() {
      return value;
   }
   public boolean isWeekend() {
      return weekend;
   }


}
于 2012-05-19T03:27:47.570 回答