ComoboBox loads and saves items automatically from a file : ComboBox « Swing JFC « Java






ComoboBox loads and saves items automatically from a file

ComoboBox loads and saves items automatically from a file
  

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class MemComboBoxDemo extends JFrame {

  protected MemComboBox urlComboBox = new MemComboBox();

  public MemComboBoxDemo() {
    super();
    setSize(300, 100);
    getContentPane().setLayout(new BorderLayout());

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    p.add(new JLabel("Address"));

    urlComboBox.load("addresses.dat");
    ComboBoxListener lst = new ComboBoxListener();
    urlComboBox.addActionListener(lst);

    MemComboAgent agent = new MemComboAgent(urlComboBox);

    p.add(urlComboBox);
    getContentPane().add(p, BorderLayout.NORTH);

    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        urlComboBox.save("addresses.dat");
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);

    setVisible(true);
    urlComboBox.grabFocus();
  }

  class ComboBoxListener implements ActionListener{
    public void actionPerformed(ActionEvent evt) {
      System.out.println( urlComboBox.getSelectedItem());
    }
  }

  public static void main(String argv[]) {
    new MemComboBoxDemo();
  }
}

class MemComboAgent extends KeyAdapter {
  protected JComboBox comboBox;

  protected JTextField editor;

  public MemComboAgent(JComboBox c) {
    comboBox = c;
    editor = (JTextField) c.getEditor().getEditorComponent();
    editor.addKeyListener(this);
  }

  public void keyReleased(KeyEvent e) {
    char ch = e.getKeyChar();
    if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch))
      return;
    int pos = editor.getCaretPosition();
    String str = editor.getText();
    if (str.length() == 0)
      return;

    for (int k = 0; k < comboBox.getItemCount(); k++) {
      String item = comboBox.getItemAt(k).toString();
      if (item.startsWith(str)) {
        editor.setText(item);
        editor.setCaretPosition(item.length());
        editor.moveCaretPosition(pos);
        break;
      }
    }
  }
}

class MemComboBox extends JComboBox {
  public static final int MAX_MEM_LEN = 30;

  public MemComboBox() {
    super();
    setEditable(true);
  }

  public void add(String item) {
    removeItem(item);
    insertItemAt(item, 0);
    setSelectedItem(item);
    if (getItemCount() > MAX_MEM_LEN)
      removeItemAt(getItemCount() - 1);
  }

  public void load(String fName) {
    try {
      if (getItemCount() > 0)
        removeAllItems();
      File f = new File(fName);
      if (!f.exists())
        return;
      FileInputStream fStream = new FileInputStream(f);
      ObjectInput stream = new ObjectInputStream(fStream);

      Object obj = stream.readObject();
      if (obj instanceof ComboBoxModel)
        setModel((ComboBoxModel) obj);

      stream.close();
      fStream.close();
    } catch (Exception e) {
      System.err.println("Serialization error: " + e.toString());
    }
  }

  public void save(String fName) {
    try {
      FileOutputStream fStream = new FileOutputStream(fName);
      ObjectOutput stream = new ObjectOutputStream(fStream);

      stream.writeObject(getModel());

      stream.flush();
      stream.close();
      fStream.close();
    } catch (Exception e) {
      System.err.println("Serialization error: " + e.toString());
    }
  }
}

           
         
    
  








Related examples in the same category

1.Combobox combines a button or editable field and a drop-down list.
2.Using drop-down listsUsing drop-down lists
3.A fancy example of JComboBox with a custom renderer and editorA fancy example of JComboBox with a custom renderer and editor
4.Editable ComboBoxEditable ComboBox
5.Create a simple combobox
6.Font Chooser ComboBoxFont Chooser ComboBox
7.Color combobox rendererColor combobox renderer
8.Select the combobox by choose the nearby labelSelect the combobox by choose the nearby label
9.Sharing a Model between a JList and JComboBoxSharing a Model between a JList and JComboBox
10.ComboBox Demo 2ComboBox Demo 2
11.Custom ComboBox with ImageCustom ComboBox with Image
12.ComboBox DemoComboBox Demo
13.List: Shared Data SampleList: Shared Data Sample
14.Selecting Combo SampleSelecting Combo Sample
15.MultiKey ComboMultiKey Combo
16.PopupCombo SamplePopupCombo Sample
17.Dual Sample: JList and ComboBoxDual Sample: JList and ComboBox
18.ComboBox SampleComboBox Sample
19.Color ComboBox: ComboBoxEditor DemoColor ComboBox: ComboBoxEditor Demo
20.Determining When the Menu of a JComboBox Component Is Displayed
21.Listening for Action Events from a JComboBox Component
22.Listening for Changes to the Selected Item in a JComboBox Component
23.Setting the Number of Visible Items in the Menu of a JComboBox Component
24.Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique
25.Displaying the Menu in a JComboBox Component Using a Keystroke
26.Determining If the Menu of a JComboBox Component Is Visible
27.Selecting an Item in a JComboBox Component with Multiple Keystrokes
28.Adding and Removing an Item in a JComboBox Component
29.Add an item after the first item
30.Add an item to the end of the list
31.Remove first item
32.Remove the last item
33.Remove all items
34.Getting the Items in a JComboBox Component
35.Getting and Setting the Selected Item in a JComboBox Component
36.If the combobox is editable, the new value can be any value
37.Creating a read-only and editable JComboBox Component
38.ArrayListComboBoxModel DemoArrayListComboBoxModel Demo
39.A frame with a sample text label and a combo box for selecting font faces