2013-04-12 80 views
0

我是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賈邁勒」 的幫助很大:

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 

    } 
} 
+0

首先,不要使用setBounds()來定位和調整組件的大小。使用佈局管理器。那麼你的問題到底是什麼?你想知道如何讀取/寫入文件?還是你問如何知道框架何時關閉? – camickr

回答

1

您可以使用文本文件讀取和寫入從中

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 
    } 
} 
+0

謝謝你的回答。我在變量定義中出現「未處理的異常類型FileNotFoundException」,Eclipse無法自動實現解決方案。你能幫我解決嗎?另外,如果文本文件與類相同,我不確定是否正確定義了文件路徑變量。我應該以某種方式包含完整的路徑嗎? –

+0

你需要firts來創建文本文件「手動」並在其上編寫你的Vectot,然後採用這個路徑並在java中讀取它,並在相同的文本路徑中再次寫入它 –

+0

我已經做到了這一點沒有問題。我不知道該把它放在哪裏以及如何定義路徑變量。應該將文本文件放在與Java類相同的路徑中,以便自動獲取它? –

0

可能在你的情況下最簡單的方法是將它們寫入文件。看看Commons IO,使文件的閱讀和寫作更容易。最好的方法是有一種初始化方法,它將讀取文件,從文件內容中填充它,然後顯示它。

然後,每當你添加一些東西到列表中,也把它寫到文件中。那麼,或者你可以去一個數據庫或者ComboBox模型的序列化,但是文件讀/寫是最容易的,IMO。

+0

謝謝你的回答。我已經閱讀過這個解決方法,但我想這會讓事情變得複雜。如果我找不到簡單的解決方案,我會改變目標。 –