java - 将添加的字符串项保存到 ComboBox

标签 java swing combobox

我是 Java 和 Swing 新手,无法找到问题的解决方案。我有一个可以将项目添加到组合框的 GUI。我试图在 GUI 关闭后将添加的项目保留在组合框中,并在再次启动时保留新添加的项目。有什么简单的方法可以做到这一点吗?

这是 GUI 的代码:

package GUI1;

import java.awt.BorderLayout;

public class OnurComboBox extends JDialog implements 
ActionListener, ItemListener {

    private final JPanel contentPanel = new JPanel();
    private JComboBox comboBox = null;
    private int comnum;
    public String combo;
//    final String[] theOptions = {
//  "Option 1", "Option 2", 
//        "Option 3", "Option 4", 
//  "Option 5", "Option 6"
//    };
    private JTextField textField;
    private JTextField textField_1;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            OnurComboBox dialog = new OnurComboBox();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the dialog.
     */
    public OnurComboBox() {



        setTitle("Choose an Option");
        setSize(325, 300);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JDesktopPane desktopPane = new JDesktopPane();
        getContentPane().add(desktopPane, BorderLayout.CENTER);

        JButton btnOk = new JButton("OK");
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {                
                System.out.println("The item selected is: " + combo);
                System.exit(0);
            }
        });
        btnOk.setBounds(66, 153, 89, 23);
        desktopPane.add(btnOk);

        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        btnCancel.setBounds(165, 153, 89, 23);
        desktopPane.add(btnCancel);

//        final JComboBox comboBox = new JComboBox(theOptions);
        Vector comboBoxItems=new Vector();
        comboBoxItems.add("A");
        comboBoxItems.add("B");
        comboBoxItems.add("C");
        comboBoxItems.add("D");
        comboBoxItems.add("E");
        final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
        final JComboBox comboBox = new JComboBox(model);
        comboBox.setBounds(10, 34, 187, 23);
        comboBox.setSelectedIndex(-1);
        comboBox.addItemListener(this);
        desktopPane.add(comboBox);
        comboBox.addItemListener(new ItemListener(){
          public void itemStateChanged(ItemEvent ie){
          combo = (String)comboBox.getSelectedItem();
          comnum = comboBox.getSelectedIndex();
          textField.setText(combo);
          }
          });

        textField = new JTextField();
        textField.setBounds(10, 228, 187, 23);
        desktopPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(10, 103, 187, 23);
        desktopPane.add(textField_1);
        textField_1.setColumns(10);

        JTextPane txtpnSelected = new JTextPane();
        txtpnSelected.setEditable(false);
        txtpnSelected.setText("Item Selected:");
        txtpnSelected.setBounds(10, 202, 89, 23);
        desktopPane.add(txtpnSelected);

        JButton btnAdd = new JButton("Add");
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!textField_1.getText().equals("")){
                      int a = 0;
                      for(int i = 0; i < comboBox.getItemCount(); i++){
                      if(comboBox.getItemAt(i).equals(textField_1.getText())){
                      a = 1;
                      break;
                      }
                      }
                      if (a == 1)
                     JOptionPane.showMessageDialog(null,"Combobox already has this item.");
                      else
                     comboBox.addItem(textField_1.getText());
                     JOptionPane.showMessageDialog(null,"Item added to Combobox");
                      }
                      else{
                      JOptionPane.showMessageDialog(null,"Please enter text in the Text Box");
                      }
                      }
                      });

        btnAdd.setBounds(207, 103, 92, 23);
        desktopPane.add(btnAdd);

        JTextPane txtpnEnterTheOption = new JTextPane();
        txtpnEnterTheOption.setText("Enter the new option:");
        txtpnEnterTheOption.setEditable(false);
        txtpnEnterTheOption.setBounds(10, 80, 131, 23);
        desktopPane.add(txtpnEnterTheOption);

        JButton btnRemove = new JButton("Remove");
        btnRemove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (comboBox.getItemCount() > 0){
                    comboBox.removeItemAt(comnum);
                    JOptionPane.showMessageDialog(null,"Item removed");}
                      else
                      JOptionPane.showMessageDialog(null,"Item not available");
            }
        });
        btnRemove.setBounds(207, 34, 92, 23);
        desktopPane.add(btnRemove);

        JTextPane txtpnSelectAnItem = new JTextPane();
        txtpnSelectAnItem.setText("Select an item from the list or add a new option");
        txtpnSelectAnItem.setBounds(10, 3, 289, 20);
        desktopPane.add(txtpnSelectAnItem);
        setVisible(true);


    }

    public void itemStateChanged(ItemEvent e) {

        if (e.getStateChange() == ItemEvent.SELECTED) {
            JComboBox combo = (JComboBox) e.getSource();
//            int index = combo.getSelectedIndex();
//            display.setIcon(new ImageIcon(
//                ClassLoader.getSystemResource(images[index])));
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}

在“Alya'a Gamal”的大力帮助下,编辑和工作的代码完成了这项工作:

package GUI1;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JDesktopPane;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JTextField;
import javax.swing.JTextPane;

public class OnurComboBox1 extends JDialog implements 
ActionListener, ItemListener {

    private final JPanel contentPanel = new JPanel();
    private JComboBox comboBox = null;
    private int comnum;
    public String combo;
    private JTextField textField;
    private JTextField textField_1;
    static String filePath = "t.txt";/////this text file have 
//    private PrintWriter out;
//    private BufferedReader input;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        try {
            OnurComboBox1 dialog = new OnurComboBox1();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the dialog.
     * @throws IOException 
     */
    public OnurComboBox1() throws IOException {

        BufferedReader input = new BufferedReader(new FileReader(filePath));  

        final PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("t.txt", true)));

        setTitle("Choose an Option");
        setSize(325, 300);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JDesktopPane desktopPane = new JDesktopPane();
        getContentPane().add(desktopPane, BorderLayout.CENTER);

        JButton btnOk = new JButton("OK");
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {                
                System.out.println("The item selected is: " + combo);
                out.close();/////to close the text file
                System.exit(0);
            }
        });
        btnOk.setBounds(66, 153, 89, 23);
        desktopPane.add(btnOk);

        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        btnCancel.setBounds(165, 153, 89, 23);
        desktopPane.add(btnCancel);

        List<String> strings = new ArrayList<String>();
        try {
            String line = null;
            try {
                while ((line = input.readLine()) != null) {
                    strings.add(line);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } finally {
            try {
                input.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

        String[] lineArray = strings.toArray(new String[]{});
        final DefaultComboBoxModel model = new DefaultComboBoxModel(lineArray);
        final JComboBox comboBox = new JComboBox(model);

        comboBox.setBounds(10, 34, 187, 23);
        comboBox.setSelectedIndex(-1);
        comboBox.addItemListener(this);
        desktopPane.add(comboBox);
        comboBox.addItemListener(new ItemListener(){
          public void itemStateChanged(ItemEvent ie){
          combo = (String)comboBox.getSelectedItem();
          comnum = comboBox.getSelectedIndex();
          textField.setText(combo);
          }
          });

        textField = new JTextField();
        textField.setBounds(10, 228, 187, 23);
        desktopPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(10, 103, 187, 23);
        desktopPane.add(textField_1);
        textField_1.setColumns(10);

        JTextPane txtpnSelected = new JTextPane();
        txtpnSelected.setEditable(false);
        txtpnSelected.setText("Item Selected:");
        txtpnSelected.setBounds(10, 202, 89, 23);
        desktopPane.add(txtpnSelected);

        JButton btnAdd = new JButton("Add");
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!textField_1.getText().equals("")){
                      int a = 0;
                      for(int i = 0; i < comboBox.getItemCount(); i++){
                      if(comboBox.getItemAt(i).equals(textField_1.getText())){
                      a = 1;
                      break;
                      }
                      }
                      if (a == 1)
                     JOptionPane.showMessageDialog(null,"Combobox already has this item.");
                      else
                     comboBox.addItem(textField_1.getText());
                     out.println(textField_1.getText());////this will add the new value in the text file
                     JOptionPane.showMessageDialog(null,"Item added to Combobox");
                      }
                      else{
                      JOptionPane.showMessageDialog(null,"Please enter text in the Text Box");
                      }
                      }
                      });

        btnAdd.setBounds(207, 103, 92, 23);
        desktopPane.add(btnAdd);

        JTextPane txtpnEnterTheOption = new JTextPane();
        txtpnEnterTheOption.setText("Enter the new option:");
        txtpnEnterTheOption.setEditable(false);
        txtpnEnterTheOption.setBounds(10, 80, 131, 23);
        desktopPane.add(txtpnEnterTheOption);

        JButton btnRemove = new JButton("Remove");
        btnRemove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (comboBox.getItemCount() > 0){
                    comboBox.removeItemAt(comnum);
                    JOptionPane.showMessageDialog(null,"Item removed");}
                      else
                      JOptionPane.showMessageDialog(null,"Item not available");
            }
        });
        btnRemove.setBounds(207, 34, 92, 23);
        desktopPane.add(btnRemove);

        JTextPane txtpnSelectAnItem = new JTextPane();
        txtpnSelectAnItem.setText("Select an item from the list or add a new option");
        txtpnSelectAnItem.setBounds(10, 3, 289, 20);
        desktopPane.add(txtpnSelectAnItem);
        setVisible(true);


    }

    public void itemStateChanged(ItemEvent e) {

        if (e.getStateChange() == ItemEvent.SELECTED) {
            JComboBox combo = (JComboBox) e.getSource();
//            int index = combo.getSelectedIndex();
//            display.setIcon(new ImageIcon(
//                ClassLoader.getSystemResource(images[index])));
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}

最佳答案

您可以使用文本文件读取和写入它

String filePath = "t.txt";/////this text file have 

1- 创建文本文件并在其上的单独行中写入您的 Vectot(A、B、C、D)

2-创建两个变量,一个用于读取文本

BufferedReader input = new BufferedReader(new FileReader(filePath));

第二个写入文件的值将被添加:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("t.txt", true)));

3- 在 comboBox 中读取此文件,如下所示:

 List<String> strings = new ArrayList<String>();
        try {
            String line = null;
            while ((line = input.readLine()) != null) {
                strings.add(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Error, file " + filePath + " didn't exist.");
        } finally {
            input.close();
        }

        String[] lineArray = strings.toArray(new String[]{});
        final DefaultComboBoxModel model = new DefaultComboBoxModel(lineArray);
        final JComboBox comboBox = new JComboBox(model);

4- 在btnAdd按钮Actionlistner中添加:

out.println(textField_1.getText());////this will add the new value in the text file

5- 在 btnOk 按钮 Actionlistner 中添加:

out.close();/////to close the text file
<小时/>
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;

class OnurComboBox extends JDialog implements
        ActionListener, ItemListener {

    private final JPanel contentPanel = new JPanel();
    private JComboBox comboBox = null;
    private int comnum;
    public String combo;
//    final String[] theOptions = {
//  "Option 1", "Option 2", 
//        "Option 3", "Option 4", 
//  "Option 5", "Option 6"
//    };
    private JTextField textField;
    private JTextField textField_1;
    String filePath = "t.txt";
     BufferedReader input = new BufferedReader(new FileReader(filePath));
public static PrintWriter out;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter("t.txt", true)));
    } catch (Exception e) {
    }

    try {
        OnurComboBox dialog = new OnurComboBox();
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
    /**
     * Create the dialog.
     */
    public OnurComboBox() throws FileNotFoundException, IOException {



        setTitle("Choose an Option");
        setSize(325, 300);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JDesktopPane desktopPane = new JDesktopPane();
        getContentPane().add(desktopPane, BorderLayout.CENTER);

        JButton btnOk = new JButton("OK");
        btnOk.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.println("The item selected is: " + combo);

                out.close();


                System.exit(0);
            }
        });
        btnOk.setBounds(66, 153, 89, 23);
        desktopPane.add(btnOk);

        JButton btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        btnCancel.setBounds(165, 153, 89, 23);
        desktopPane.add(btnCancel);

//        final JComboBox comboBox = new JComboBox(theOptions);

        List<String> strings = new ArrayList<String>();
        try {
            String line = null;
            while ((line = input.readLine()) != null) {
                strings.add(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Error, file " + filePath + " didn't exist.");
        } finally {
            input.close();
        }

        String[] lineArray = strings.toArray(new String[]{});
        final DefaultComboBoxModel model = new DefaultComboBoxModel(lineArray);
        final JComboBox comboBox = new JComboBox(model);
        comboBox.setBounds(10, 34, 187, 23);
        comboBox.setSelectedIndex(-1);
        comboBox.addItemListener(this);
        desktopPane.add(comboBox);
        comboBox.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent ie) {
                combo = (String) comboBox.getSelectedItem();
                comnum = comboBox.getSelectedIndex();
                textField.setText(combo);
            }
        });

        textField = new JTextField();
        textField.setBounds(10, 228, 187, 23);
        desktopPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(10, 103, 187, 23);
        desktopPane.add(textField_1);
        textField_1.setColumns(10);

        JTextPane txtpnSelected = new JTextPane();
        txtpnSelected.setEditable(false);
        txtpnSelected.setText("Item Selected:");
        txtpnSelected.setBounds(10, 202, 89, 23);
        desktopPane.add(txtpnSelected);

        JButton btnAdd = new JButton("Add");
        btnAdd.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (!textField_1.getText().equals("")) {
                    int a = 0;
                    for (int i = 0; i < comboBox.getItemCount(); i++) {
                        if (comboBox.getItemAt(i).equals(textField_1.getText())) {
                            a = 1;
                            break;
                        }
                    }
                    if (a == 1) {
                        JOptionPane.showMessageDialog(null, "Combobox already has this item.");
                    } else {
                        comboBox.addItem(textField_1.getText());
                    }

                    out.println(textField_1.getText());


                    JOptionPane.showMessageDialog(null, "Item added to Combobox");
                } else {
                    JOptionPane.showMessageDialog(null, "Please enter text in the Text Box");
                }
            }
        });

        btnAdd.setBounds(207, 103, 92, 23);
        desktopPane.add(btnAdd);

        JTextPane txtpnEnterTheOption = new JTextPane();
        txtpnEnterTheOption.setText("Enter the new option:");
        txtpnEnterTheOption.setEditable(false);
        txtpnEnterTheOption.setBounds(10, 80, 131, 23);
        desktopPane.add(txtpnEnterTheOption);

        JButton btnRemove = new JButton("Remove");
        btnRemove.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (comboBox.getItemCount() > 0) {
                    comboBox.removeItemAt(comnum);
                    JOptionPane.showMessageDialog(null, "Item removed");
                } else {
                    JOptionPane.showMessageDialog(null, "Item not available");
                }
            }
        });
        btnRemove.setBounds(207, 34, 92, 23);
        desktopPane.add(btnRemove);

        JTextPane txtpnSelectAnItem = new JTextPane();
        txtpnSelectAnItem.setText("Select an item from the list or add a new option");
        txtpnSelectAnItem.setBounds(10, 3, 289, 20);
        desktopPane.add(txtpnSelectAnItem);
        setVisible(true);


    }

    public void itemStateChanged(ItemEvent e) {

        if (e.getStateChange() == ItemEvent.SELECTED) {
            JComboBox combo = (JComboBox) e.getSource();
//            int index = combo.getSelectedIndex();
//            display.setIcon(new ImageIcon(
//                ClassLoader.getSystemResource(images[index])));
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }
}

关于java - 将添加的字符串项保存到 ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15976565/

相关文章:

java - 在移动设备上禁用缩放

java - SAAJ0539/SAAJ0540 : disagreement between Spring-WS 1. 0.4 和 JDK 1.6.0_29 中的 SAAJ

java - 在 JFrame 中将固定大小的 Canvas 居中

组件可见时的java事件

c# - ComboBox 和 TextBox 之间的连接

java - 构造子串的字符串操作

java - 无法创建 MD5 哈希文件?

Java GUI元素设计

c# - 当我在组合框中选择一个项目时如何防止 TextChanged 事件?

javascript - 我无法让这个 Jquery Image ComboBox 工作