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 に答える