【问题标题】:Use a JComboBox to call information from an array?使用 JComboBox 从数组中调用信息?
【发布时间】:2012-05-19 03:25:29
【问题描述】:

如何从 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
}

}

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

【问题讨论】:

  • 请将代码示例缩小到实际相关的部分。

标签: java arrays swing jcombobox


【解决方案1】:

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

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

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

  //...
}

然后创建JComboBox&lt;MyContact&gt;

当一个item被选中时,调用对应的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;
   }


}

【讨论】:

  • 感谢气垫船。我从没想过这样做。我是 Java 新手,希望我能控制它。
  • 从文件中读取数据时如何用对象填充组合框?
  • @nege0:这完全取决于文件的组织方式。通常,每个对象的数据都保存在文件的一行中。因此,您阅读该行,提取信息,使用该信息创建一个对象,并将其添加到组合模型中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2021-11-29
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多