SetEditable(false)

Hai..
I have a TextField called tf1
based on the setEditable(false) method i have to do some code like this
Is it possible to do like this ? or is there any other option to validate like this
I am new to java
please help me.
Thanks in advance
Yours
Rajesh
if (tf1==setEditable(false))
System.out.println("Textfield is not Editable");
else
System.out.println("Textfield is Editable");
}

Rajesh
Hi,
The setEditable() method does not return a boolean. setEditable()
is for setting a TextField editable.
tf1.setEditable(true);
isEditable() returns a boolean.
tf1.isEditable() returns true if tf1 is editable, flase if tf1 is not editable.
Deepak

Similar Messages

  • Inserting Icons in JTextPane with setEditable=false

    Aloha!
    I'm working on this for years now, but i haven't found an acceptable solution yet.
    The problem: I have a JTextPane, where the user shall not be able to edit anything by clicking onto the JTextPane. So I have to setEditable=false. Now I want to insert an icon with insertIcon and therefore i have to setEditable = true. But for short time it's now possible for the user to click onto the screen and change the caretPosition, which must be prevented at all costs (because I'm working with the expected caretPosition of course)! This only happens when I try the brute force testing method, but it happens sometimes...
    So can someone give me a better solution than:
    setEditable = true;
    insertIcon(blahblah);
    setEditable = false;
    Thanks a lot for your attention,
    Holm

    To use HTML, you must use javax.swing.text.html.HTMLDocument instead of StyledDocument,
    Instead of StyleConstants, you must use javax.swing.text.html.HTML$Tag and javax.swing.text.html.HTML$Attribute.
    And you can use an HTMLEditorKit instead of DefaultEditorKit.
    this is an example of initialization:
    javax.swing.text.html.HTMLEditorKit htmlEditorKit = new javax.swing.text.html.HTMLEditorKit();
    javax.swing.text.html.HTMLDocument htmlDoc = (javax.swing.text.html.HTMLDocument)htmlEditorKit.createDefaultDocument();
    yourJTextPane.setEditorKit(htmlEditorKit);
    yourJTextPane.setDocument(htmlDoc);
    yourJTextPane.setEditable(true);
    yourJTextPane.setContentType("text/html");and you can use it by yourJTextPane.setText(HtmlCodeString)
    HTMLDocument and HTMLEditorKit allow you main modifications.
    thanks for duke dollars :)

  • Why doesn't calling setEditable(false) disable cursoring

    I want to have JFormattedTextField format my date fields for me. It does a good job of it, so why wouldn't I?
    I have a need to display a non-editable date for reference purposes. Unfortunately I discovered that the cursoring is still active when setEditable(false) is called. In order to prevent this, I have had to subclass DateFormatter in order to override getActions() to return null if I don't want incrementing. There are a number of problems with this:
    1) setEditable on JFormattedTextField should have been enough. If I don't want it editable, then I don't want cursoring. I would have thought that was obvious.
    2) Notwithstanding that, the correct method to override for incrementing is really getSupportsIncrement(), but this has no modifier, so is in the 'friendly' status, which means it can only be overridden in the package.
    3) While I can override getActions, this signature leaves itself open to have other actions than "increment" and "decrement" returned . That is, it works now, but if sun adds more actions to the list of actions returned by getActions(), then my override is broken.
    Is there a bug in there somewhere?
    Thanks, Andrew

    1) setEditable on JFormattedTextField should have
    been enough. If I don't want it editable, then I
    don't want cursoring. I would have thought that was
    obvious.Nope not really. What if the user wants to copy some text using the keyboard?

  • Visually express setEditable(false)

    Hello,
    On the GUI I write, if a user clicks an a radio button, a text field must not be editable anymore. It works with setEditable(false) but it has no graphical effect.
    So Is there a way to put the text field and its associate label in gray?
    I searched the API and various doc, but found nothing.
    Thanks for help
    Thierry

    Like setBackGround and setForeGround.

  • JTextComponent - setEditable background color

    I have a subclass of JTextField. I am doing manipulations of the background color (red when validation failed). When the program sets the text field to be not editable I want the default disabled background color (transparent?) to be displayed.
    However, in some cases I am getting a background of white when it is disabled.
    What is setEditable doing to change the background from white to grey? If I have the background color set to RED how do I change it so that grey will be shown?
    Thanks,
    John

    I am trying to understand what setEditable does WRT the background color / transpanency. In the below code, when you press the button the first time, the background of the textfield becomes grey. If you press it again it becomes white. Is this because setEditable doesn't do anything if the field is already editable?
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class BackgroundTester extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JPanel jPanel = null;
         private JTextField jTextField = null;
         private JButton jButton = null;
         private Color origBackColor = null;
          * This method initializes jPanel     
          * @return javax.swing.JPanel     
         private JPanel getJPanel() {
              if (jPanel == null) {
                   GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
                   gridBagConstraints2.gridx = 0;
                   gridBagConstraints2.gridy = 2;
                   GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                   gridBagConstraints1.fill = GridBagConstraints.VERTICAL;
                   gridBagConstraints1.gridy = 1;
                   gridBagConstraints1.weightx = 1.0;
                   gridBagConstraints1.gridx = 0;
                   jPanel = new JPanel();
                   jPanel.setLayout(new GridBagLayout());
                   jPanel.add(getJTextField(), gridBagConstraints1);
                   jPanel.add(getJButton(), gridBagConstraints2);
              return jPanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField     
         private JTextField getJTextField() {
              if (jTextField == null) {
                   jTextField = new JTextField();
                   jTextField.setColumns(10);
              return jTextField;
          * This method initializes jButton     
          * @return javax.swing.JButton     
         private JButton getJButton() {
              if (jButton == null) {
                   jButton = new JButton();
                   jButton.setText("Set Disabled");
                   jButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             jTextField.setBackground(origBackColor);
                             jTextField.setEditable(false);
              return jButton;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        BackgroundTester thisClass = new BackgroundTester();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
          * This is the default constructor
         public BackgroundTester() {
              super();
              initialize();
              origBackColor = jTextField.getBackground();
              jTextField.setBackground(Color.RED);
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getJPanel(), BorderLayout.CENTER);
              return jContentPane;
    }

  • JTextField's - setting editable false, but without greying out the area?

    Is this at all possible? Is there any other way to go about it? Or is the only way to make a textfeild un-edditable using the setEditable(false); command.. and sticking it with the grey area?
    Sorry for the weird/dumb/annoying question..
    Thanks anyway heh..

    all i wanted was an answer and this dude just flames
    me.I think your need to adjust your sensitivity downward by an order of magnitude. I didn't see anything in Joachim's response that remotely resembled a flame. He simply pointed out that your requested goal violates standard usability principles (rather politely, I might add). You referred to your own question in a more derogatory manner than any respondent.
    Personally, I think his advice was very helpful. You shouldn't violate standard usability principles unless you're just deliberately trying to confuse your users, which is not something many of us would care to give advice on how to do...

  • SetEditable is not working with combobox

    Hi,
    I am working with table and using combo box in cell of table, in certain condition I have to make combo as editable and non editable.
    I have written class which extends DefaultCellEditor
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean flag, int row, int column)
    comboBox.getModel()).setSelectedItem(value.toString());
    comboBox.setEditable(true);
    if i set comboBox.setEditable(true). cell become editable but i am not able to select item from combo..
    when i do set comboBox.setEditable(false) cell become non editable and i can select value from combo but not able to enter any value.
    i want both the operations. Editable cell in which user can enter any value and also can select value from combo.
    Any Idea???? please share with me, this is blocking issue for me. Thanks in advance.
    Prashant Gour
    Message was edited by:
    Prashant_SDN

    thanks
    that is working idea of key listener. now i am able to select item form combo and can enter value too. but now problem is that by default combo looks non editable and become editable after pressing key .
    so that is looked user friendly.
    have you any suggestions.

  • JTextFeild.setEditable funny behaviour

    Hey Guys I hope someone can help me as I'm completely stuck to whether this is a bug or whether I'm just missing something. Given the following code:
    private void setComponentState( int state )
    switch(state)
    case 1:
    btnSearch.setEnabled( true ); //JButton
    btnReplace.setEnabled( false ); //JButton
    txtBarcodeReplc.setEditable( false ); //JTextFeild
    break;
    case 2:
    btnSearch.setEnabled( false ); //JButton
    btnReplace.setEnabled( true ); //JButton
    txtBarcodeReplc.setEditable( true ); //JTextFeild
    break;
    The problem I'm having is that everything works fine until the 3rd or sometimes the 4th time I call this method with a state=2 param. At this point the txtBarcodeReplc control refuses to enable itself. It changes color as it should and when the properties of the control are queried, the control thinks it's enabled, it's just that you cannot type anything or select inside the control. Interestingly enough, if I remove the calls to the other 2 jbutton controls so that the only thing this method does is reset my JTextFeild control, then it works perfectly fine. I'm curerntly using 1.3.1_09.
    Hope someone has some idea's to how to solve this as I'm completely stumped

    Apologies - the problem I was getting at is that it is unsafe to make calls on Swing components from any thread other than the Swing thread. This is unlikely when you are new to Java.
    As for your problem - you can search the bug database. Does http://developer.java.sun.com/developer/bugParade/bugs/4680302.html look like your problem? If so then the latest version looks to be your only option, or try putting the text field in front (in tab order) of the buttons.

  • SetEditable

    I have a class project that the user is to only input 10 numbers. I thought it would be cool to after the 10 numbers where entered to change the Editable field to false. When I did that I get an errors after the 10th number entered. How can I stop the errors or am I should I do something different instead of the setEditable(false)?
    This is my code
    // Purpose - Use an array to hold numbers entered and display only ones that are not duplicates.
    // Java Graphics package
    import java.awt.*;
    import java.awt.event.*;
    // Java extension packages
    import javax.swing.*;
    public class Assignment7_13 extends JApplet implements ActionListener {
    int numarray [] = new int[19];      // holds arrary from input
    String display = "";
    boolean firsttime = true ;
    int cntarray = 0;
    // Labels for user interface
    JLabel numlabel;
    JTextField numfield;
    JTextArea output;
    // init method
    public void init()
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    numlabel = new JLabel("Enter integer from 10 - 100");
    c.add(numlabel);
    numfield = new JTextField(5);
    c.add(numfield);
    numfield.addActionListener(this);
    // Setup textarea for output
    output = new JTextArea(2,20);
    c.add(output);
    } // end int method
    // process input
    public void actionPerformed(ActionEvent e)
         int numinput = 0;
         int found = 0;
         if (cntarray <=10){
              numinput = Integer.parseInt(numfield.getText());
              if (numinput > 9 && numinput <101){
                   found = linearSearch(numinput);
                   if (found == -1 ){
                        numarray[cntarray] = numinput;
                        cntarray++;
                        display += Integer.toString(numinput) + " " ;
                        output.setText(display);
                   } // end of if
              }// end if
         } // end if
         numfield.setText("");
         if (cntarray >= 10)
         numfield.setEditable(false);
    } // end actionPerformed method
    // Search array for specified key value
    public int linearSearch( int key )
    // loop through array elements
    for ( int counter = 0; counter < numarray.length; counter++ )
    // if array element equals key value, return location
    if ( numarray[ counter ] == key )
    return counter;
    return -1; // key not found
    } // end class Assignment7_13

    Hi,
    You have an error in checking the boundary.
    The line:
    if (cntarray<=10) {should be
    if (cntarray<10) {Regards,
    S&oslash;ren

  • Problem with threads in my swing application

    Hi,
    I have some problem in running my swing app. Thre problem is related to threads.
    What i am developing, is a gui framework where i can add different pluggable components to the framework.
    The framework is working fine, but when i press the close action then the gui should close down the present component which is active. The close action is of the framework and the component has the responsibility of checking if it's work is saved or not and hence to throw a message for saving the work, therefore, what i have done is that i call the close method for the component in a separate thread and from my main thread i call the join method for the component's thread.But after join the whole gui hangs.
    I think after the join method even the GUI thread , which is started for every gui, also waits for the component's thread to finish but the component thread can't finish because the gui thread is also waiting for the component to finish. This creates a deadlock situation.
    I dont know wht's happening it's purely my guess.
    One more thing. Why i am calling the component through a different thread, is because , if the component's work is not saved by the user then it must throw a message to save the work. If i continue this message throwing in my main thread only then the main thread doesnt wait for user press of the yes no or cancel button for saving the work . It immediately progresses to the next statement.
    Can anybody help me get out of this?
    Regards,
    amazing_java

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Open web pages from an applet

    I'm developing an applet that has to open some web pages.
    The only way I know is to use the method showDocument that
    needs and URL. So, how to pass parameters to the web page?
    I don't want to put them in the URL: everyone can see
    "secret data"!
    Help me, please.

    Take a look at this example that uses a JEditor pane to hold the HTML page.
    //Create a new JEditor Pane
    jep = new JEditorPane( );
    //Ensure the pane is not editable
    jep.setEditable(false);  
    //Use this to get local HTML file
    URL fileURL = this.getClass().getResource("Manual/Manual.htm");
    //add the html page to the JEditorPane
    jep.setPage(fileURL);Ok the core line of code here is this.
    URL fileURL = this.getClass().getResource("Manual/Manual.htm");The standard method for accessing a html file via a URL is thus. As you can see its very similar.
    URL fileURL = new URL("http://www.comp.glam.ac.uk/pages/staff/asscott/progranimate/docs/Manual/Manual.htm");this.getClass().getResourse() will return the file location of the class you are working with.
    By doing the following you can access manual.html in a folder called Manual that sits in the same file location as the class file you are using.
    URL fileURL = this.getClass().getResource("Manual/Manual.htm");I hope this helps.
    Andrew.

  • Address book .... importing text file

    I am designing an address book which opens a text file called AddressBook.txt which reads in the information in the following format:
    lastname,firstname,street,city,state,zip,phonenumber,birthday,persontype
    lastname2,firstname2,street2,city2,state2,zip2,phonenumber2,birthday2,persontype2
    etc. (with a maximum entries of 500)
    I am having a problem reading in the information without the commas and wrapping to the next line. I can either use the BufferedReader or Scanner to input the file and as you can see below, my code is not complete yet. I can't figure out how to code the storeAddress() method in order to get the addressBookEntries[] to include the necessary information for outputting, sorting, etc. If I can get the information read into the addressBookEntries[], I think I will probably be able to proceed in the rest of the required tasks (i.e. sorting by last name, searching by last name, etc.)
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    *  @created September 14, 2004
    *  This program uses a JFrame to manipulate data and form an
    *  address book.  The user will be able to load data from a file,
    *  sort it by last name, print the address, phone number, and date
    *  of birth, print the names of people whos birthday are between 2
    *  dates, print the names of people between 2 last names, and/or
    *  print the names of different person types.
    public class AddressBook extends JPanel implements ActionListener{
        JFrame frame;
        final int numButtons = 7;
        JRadioButton[] radioButtons = new JRadioButton[numButtons];
        JButton process = new JButton("Process Request");
        JLabel title;
        JTextArea output = new JTextArea(30,50);
        int MAX_ADDRESS_ENTRIES = 500;
        AddressBookEntry addressBookEntries[] =
            new AddressBookEntry[MAX_ADDRESS_ENTRIES];
        String FILE_NAME="AddressBook.txt";
        public AddressBook(JFrame frame){
            super(new BorderLayout());
            this.frame=frame;
            JPanel choicePanel = createSimpleDialogBox();
            choicePanel.setBorder(BorderFactory.createTitledBorder("Choices" +
            " to choose from:"));
            title = new JLabel("<html><h2> Thank you for opening the " +
            "Address Book.  " +
            "Please Press the \"Process Request\" " +
            "after making a choice.</h2></html>\n",JLabel.CENTER);
            title.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
            output.setEditable(false);
            add(title, BorderLayout.NORTH);
            add(choicePanel, BorderLayout.CENTER);
            add(output, BorderLayout.SOUTH);
            final ButtonGroup group = new ButtonGroup();
            final String saveCommand = "Save";
            final String sortByLN = "Sort by Last Name";
            final String searchLNCommand = "Search By Last Name";
            final String printAPD = "Print address, phone number, and DOB";
            final String printNamesDOB = "Print names of people whose birthday" +
            " falls between 2 dates";
            final String printNamesLN = "Print names of people who fall" +
            " between 2 last names";
            final String printPType = "Print all family members, friends, or" +
            " business associates";
        private JPanel createSimpleDialogBox(){
            radioButtons[0] = new JRadioButton(
              "<html>Save the address file</html>");
            radioButtons[0].setActionCommand(saveCommand);
            radioButtons[1] = new JRadioButton(
              "<html>Sort the address file by last name</html>");
            radioButtons[1].setActionCommand(sortByLN);
            radioButtons[2] = new JRadioButton(
              "<html>Search the address file by last name</html>");
            radioButtons[2].setActionCommand(searchLNCommand);
            radioButtons[3] = new JRadioButton(
              "<html>Print the address, phone number, and DOB of a specified" +
              " person</html>");
            radioButtons[3].setActionCommand(printAPD);
            radioButtons[4] = new JRadioButton(
              "<html>Print the names of people whose birthday falls between" +
              " two dates</html>");
            radioButtons[4].setActionCommand(printNamesDOB);
            radioButtons[5] = new JRadioButton(
              "<html>Print the names of people who fall between two" +
              " specified last names</html>");
            radioButtons[5].setActionCommand(printNamesLN);
            radioButtons[6] = new JRadioButton(
              "<html>Print all family members, friends, <u>OR</u>" +
              " business associates</html>");
            radioButtons[6].setActionCommand(printPType);
            for (int i=0; i<numButtons; i++){
                group.add(radioButtons);
    //set the first button (open file) to be selected
    radioButtons[0].setSelected(true);
    return createPane(radioButtons, process);
    private JPanel createPane(JRadioButton[] radioButtons,
    JButton showButton) {
    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    for (int i = 0; i < numChoices; i++) {
    box.add(radioButtons[i]);
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.NORTH);
    pane.add(showButton, BorderLayout.SOUTH);
    return pane;
    public void actionPerformed(ActionEvent e) {
    String command = group.getSelection().getActionCommand();
    //else if button pushed is save
    if (command == saveCommand){
    // save file
    //else if button pushed is search by last name
    else if (command == sortByLN){
    // search by last name
    //else if button pushed is sort by last name
    else if (command == searchLNCommand){
    // sort by last name
    // print to screen
    //else if button pushed is display address, ph#, dob
    else if (command == printAPD){
    // display "search by last name" dialog
    // search last names
    // if last name found
    // print data
    // else
    // print error notification "person not found"
    //else if button pushed is list names of people whose
    //bday between 2 days
    else if (command == printNamesDOB){
    // ask for which dates
    // search bday
    // print to screen
    //else if button pushed is print names of people between 2 last names
    else if (command == printNamesDOB){
    // ask for which two last names
    // search last names
    // if people found
    // print to screen
    //else
    //print error notification "no one found"
    //else if button pushed is print all family members, friends
    //or business associates
    else if (command == printPType){
    //ask for what person type
    //search person types
    //if people found
    //print to screen
    //else print "no one found"
    public void storeAddress(File addressFile){
         Scanner sc=null;
    String lname,fname,street,city,state,zip,phone,persontype,bday;
    try {
    // Delimiters specifiy where to parse tokens in a scanner
    sc = new Scanner(addressFile).useDelimiter("\\s*[\\p{,}*\\s+]\\s*");
    catch (FileNotFoundException fnfe) {
         JOptionPane.showMessageDialog(this,"Could not open the file");
    System.exit(-1);
    for(int i=0; i<MAX_ADDRESS_ENTRIES; i++){
         while (sc.hasNext()) {
    lname=(sc.next());
         if (!lname.equals("")){
         addressBookEntries[i].setLName()=lname;
    public class AddressBookEntry{
    private extPerson address;
    private String date;
    private extPerson ExtPerson;
    public class Person{
    protected String lastName, firstName;
    private String address;
    private String city;
    private String state;
    private String zipcode;
    private String homephone;
    private String extPersonType;
    private Date bday;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-DD");
    public String toString() {
    return lastName+" "+firstName;
    public void setLName(String last) {
    lastName=last;
    public void setFName(String first){
    firstName=first;
    public String getLastName() {
    return lastName;
    public String getFirstName() {
    return lastName;
    public Person() {
    lastName="";
    firstName="";
    public Person(String first, String last){
    setLName(last);
    setFName(first);
    //Set the address and return it
    public void setAddress( String addr ){
    address = addr;
    public String getAddress(){
    return address;
    //set the city and return it
    public void setCity( String town ){
    city = town;
    public String getCity(){
    return city;
    //set the state and return it
    public void setState( String st )
    state = st;
    public String getState()
    return state;
    //Set the zip code and return it
    public void setZipCode( String zip ){
    zipcode = zip;
    public String getZipCode(){
    return zipcode;
    //Set the home phone and return it
    public void setHomePhone( String homeph ){
    homephone = homeph;
    public String getHomePhone(){
    return homephone;
    //Set the bday and return it
    public Date getBday(){
    return bday;
    public void setBday(Date newBday) {
    bday = newBday;
    dateFormat.format(bday);
    //Set the extPerson type and return it
    public String getPType(){
    return extPersonType;
    public void setPBusiness(){
    extPersonType = "Business Associate";
    public void setPFamily(){
    extPersonType = "Family Member";
    public void setPFriend(){
    extPersonType = "Friend";
    public class extPerson extends Person{
    //new clss People
    public class People {
         int MAX_PEOPLE=500;
         BufferedReader bf;
    public String toString() {
              StringBuffer sb=new StringBuffer();
              for (int i=0; i<nPeople; i++)
              sb=sb.append(group[i]+"\n");
              return sb.toString();
    public void read(){
              String str;
              try {
              bf=new BufferedReader(new FileReader(new File(FILE_NAME)));
              str=bf.readLine();
              while (str!=null) {
              insert(str);
                   str=bf.readLine();
         catch (IOException e) {
              // Will jump to here on an eof condition.
         try {
              bf.close();
         catch (IOException e) {}
         public void save() {
              try {
              PrintWriter pw=new PrintWriter(FILE_NAME);
              for (int i=0; i<nPeople; i++)
              pw.println(group[i]+",");
              pw.close();
         catch (FileNotFoundException fne) {
                   System.out.println("Could not Save "+FILE_NAME);
    public People() {
              group=new extPerson[MAX_PEOPLE];
              nPeople=0;
         public boolean insert(String data) {
              if (nPeople<MAX_PEOPLE) {
              //extPerson guy=new extPerson(data);
              //group[nPeople]=guy;
              nPeople++;
              return true;
         else {
         JOptionPane.showMessageDialog(null,"Error in People" +
    "::insert: Max size reached.");
         return false;
         public void clear() {
              // This loop frees up the memory used by each extPerson
              for (int i=0; i<nPeople; i++)
              group[i]=null;
              nPeople=0;
    extPerson group[];
    int nPeople;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    public static void createAndShowGUI(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Address Book Program");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane();
    c.add(new AddressBook(frame));
    frame.pack();
    frame.setVisible(true);
    public static void main (String s[]){       
    //Schedule a job for the event-dispatching thread:
    //creating and showign this application's GUI
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Ok, I have changed my code to reflect your suggested changes, but I'm still unsure how to use the findInLine you suggested.... This is all very new to me and I've been looking on the java website for suggestions, but I'm still stumped on how to pull this together. I'm unsure on how to set the lastname,firstname,etc. for retrieval...
    Here's my code:
    //ADDRESS BOOK
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    *  @created September 14, 2004
    *  This program uses a JFrame to manipulate data and form an
    *  address book.  The user will be able to load data from a file,
    *  sort it by last name, print the address, phone number, and date
    *  of birth, print the names of people whos birthday are between 2
    *  dates, print the names of people between 2 last names, and/or
    *  print the names of different person types.
    public class AddressBook extends JPanel implements ActionListener{
        JFrame frame;
        final int numButtons = 7;
        JRadioButton[] radioButtons = new JRadioButton[numButtons];
        JButton process = new JButton("Process Request");
        JLabel title;
        JTextArea output = new JTextArea(30,50);
        int MAX_ADDRESS_ENTRIES = 500;
        AddressBookEntry addressBookEntries[] = new
        AddressBookEntry[MAX_ADDRESS_ENTRIES];
        public AddressBook(JFrame frame){
            super(new BorderLayout());
            this.frame=frame;
            JPanel choicePanel = createSimpleDialogBox();
            choicePanel.setBorder(BorderFactory.createTitledBorder("Choices" +
            " to choose from:"));
            title = new JLabel("<html><h2> Thank you for opening the " +
            "Address Book.  " +
            "Please Press the \"Process Request\" " +
            "after making a choice.</h2></html>\n",JLabel.CENTER);
            title.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
            output.setEditable(false);
            add(title, BorderLayout.NORTH);
            add(choicePanel, BorderLayout.CENTER);
            add(output, BorderLayout.SOUTH);
            final ButtonGroup group = new ButtonGroup();
            final String saveCommand = "Save";
            final String sortByLN = "Sort by Last Name";
            final String searchLNCommand = "Search By Last Name";
            final String printAPD = "Print address, phone number, and DOB";
            final String printNamesDOB = "Print names of people whose birthday" +
            " falls between 2 dates";
            final String printNamesLN = "Print names of people who fall" +
            " between 2 last names";
            final String printPType = "Print all family members, friends, or" +
            " business associates";
        private JPanel createSimpleDialogBox(){
            radioButtons[0] = new JRadioButton(
              "<html>Save the address file</html>");
            radioButtons[0].setActionCommand(saveCommand);
            radioButtons[1] = new JRadioButton(
              "<html>Sort the address file by last name</html>");
            radioButtons[1].setActionCommand(sortByLN);
            radioButtons[2] = new JRadioButton(
              "<html>Search the address file by last name</html>");
            radioButtons[2].setActionCommand(searchLNCommand);
            radioButtons[3] = new JRadioButton(
              "<html>Print the address, phone number, and DOB of a specified" +
              " person</html>");
            radioButtons[3].setActionCommand(printAPD);
            radioButtons[4] = new JRadioButton(
              "<html>Print the names of people whose birthday falls between" +
              " two dates</html>");
            radioButtons[4].setActionCommand(printNamesDOB);
            radioButtons[5] = new JRadioButton(
              "<html>Print the names of people who fall between two" +
              " specified last names</html>");
            radioButtons[5].setActionCommand(printNamesLN);
            radioButtons[6] = new JRadioButton(
              "<html>Print all family members, friends, <u>OR</u>" +
              " business associates</html>");
            radioButtons[6].setActionCommand(printPType);
            for (int i=0; i<numButtons; i++){
                group.add(radioButtons);
    //set the first button (open file) to be selected
    radioButtons[0].setSelected(true);
    return createPane(radioButtons, process);
    private JPanel createPane(JRadioButton[] radioButtons,
    JButton showButton) {
    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    for (int i = 0; i < numChoices; i++) {
    box.add(radioButtons[i]);
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.NORTH);
    pane.add(showButton, BorderLayout.SOUTH);
    return pane;
    public void actionPerformed(ActionEvent e) {
    String command = group.getSelection().getActionCommand();
    //else if button pushed is save
    if (command == saveCommand){
    // save file
    //else if button pushed is search by last name
    else if (command == sortByLN){
    // search by last name
    //else if button pushed is sort by last name
    else if (command == searchLNCommand){
    // sort by last name
    // print to screen
    //else if button pushed is display address, ph#, dob
    else if (command == printAPD){
    // display "search by last name" dialog
    // search last names
    // if last name found
    // print data
    // else
    // print error notification "person not found"
    //else if button pushed is list names of people whose
    //bday between 2 days
    else if (command == printNamesDOB){
    // ask for which dates
    // search bday
    // print to screen
    //else if button pushed is print names of people between 2 last names
    else if (command == printNamesDOB){
    // ask for which two last names
    // search last names
    // if people found
    // print to screen
    //else
    //print error notification "no one found"
    //else if button pushed is print all family members, friends
    //or business associates
    else if (command == printPType){
    //ask for what person type
    //search person types
    //if people found
    //print to screen
    //else print "no one found"
    public class AddressBookEntry{
    private extPerson address;
    private String date;
    private extPerson ExtPerson;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    public static void createAndShowGUI(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Address Book Program");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane();
    c.add(new AddressBook(frame));
    frame.pack();
    frame.setVisible(true);
    public static void main (String s[]){       
    //Schedule a job for the event-dispatching thread:
    //creating and showign this application's GUI
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    //PERSON
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    public class Person{
    protected String lastName, firstName;
    private String address;
    private String city;
    private String state;
    private String zipcode;
    private String homephone;
    private String extPersonType;
    private String bday;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-DD");
    public void parseString(String s) {
              try {
              lastName = s.substring(0,s.indexOf(","));
              firstName = s.substring(s.indexOf(",")+1);
    address = s.substring(s.indexOf(",")+2);
    city = s.substring(s.indexOf(",")+3);
    state = s.substring(s.indexOf(",")+4);
    zipcode = s.substring(s.indexOf(",")+5);
    homephone = s.substring(s.indexOf(",")+6);
    extPersonType = s.substring(s.indexOf(",")+7);
    bday = s.substring(s.indexOf(",")+8);
    catch(StringIndexOutOfBoundsException sbe) {
              JOptionPane.showMessageDialog(null,"Error " +
    "in Person: Could not parse the line "+s);
    public String toString() {
    return lastName+","+firstName+","+address+","+city+","+
    state+","+zipcode+","+homephone+","+bday+","+extPersonType;
    public void setLName(String last) {
    lastName=last;
    public void setFName(String first){
    firstName=first;
    public String getLastName() {
    return lastName;
    public String getFirstName() {
    return lastName;
    public Person() {
    lastName="";
    firstName="";
    public Person(String first, String last){
    setLName(last);
    setFName(first);
    //Set the address and return it
    public void setAddress( String addr ){
    address = addr;
    public String getAddress(){
    return address;
    //set the city and return it
    public void setCity( String town ){
    city = town;
    public String getCity(){
    return city;
    //set the state and return it
    public void setState( String st )
    state = st;
    public String getState()
    return state;
    //Set the zip code and return it
    public void setZipCode( String zip ){
    zipcode = zip;
    public String getZipCode(){
    return zipcode;
    //Set the home phone and return it
    public void setHomePhone( String homeph ){
    homephone = homeph;
    public String getHomePhone(){
    return homephone;
    //Set the bday and return it
    public String getBday(){
    return bday;
    public void setBday(String newBday) {
    bday = newBday;
    dateFormat.format(bday);
    //Set the extPerson type and return it
    public String getPType(){
    return extPersonType;
    public void setPBusiness(){
    extPersonType = "Business Associate";
    public void setPFamily(){
    extPersonType = "Family Member";
    public void setPFriend(){
    extPersonType = "Friend";
    public Person(String data) {
    parseString(data);
    //EXTPERSON
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.io.*;
    import java.lang.*;
    //new clss extPerson
    public class extPerson extends Person {       
         int MAX_PEOPLE=500;
         BufferedReader bf;
    String lname,fname,street,city,state,zip,phone,persontype,bday;
    String FILE_NAME="AddressBook.txt";
    public String toString() {
              StringBuffer sb=new StringBuffer();
              for (int i=0; i<nPeople; i++)
              sb=sb.append(group1[i]+"\n");
              return sb.toString();
         public void save() {
              try {
              PrintWriter pw=new PrintWriter(FILE_NAME);
              for (int i=0; i<nPeople; i++)
              pw.println(group1[i]+",");
              pw.close();
         catch (FileNotFoundException fne) {
                   System.out.println("Could not Save "+FILE_NAME);
    public extPerson() {
              group1=new extPerson[MAX_PEOPLE];
              nPeople=0;
         public boolean insert(String data) {
              if (nPeople<MAX_PEOPLE) {
              Person guy = new Person(data);
              group1[nPeople]=guy;
              nPeople++;
              return true;
         else {
         JOptionPane.showMessageDialog(null,"Error in People" +
    "::insert: Max size reached.");
         return false;
    Person group1[];
    int nPeople;

  • I am really sorry but I am still stuck. Please help.

    Please can someone help me with the following code. I have a number of questions. So far all buttons that I have coded actions for work fine. When The program saves it does it correctly as I have seen the text file. However I have some problems.
    1) How can I declare the arrays in another way without setting them to "" when the program starts. I need the program to start and show the previous saved arrays instead. I dont know if my method used for retrieving data from the file is correct either?.
    2) When retrieving the values from a file that has example (all are string values). ADAM SANDLER 111 222 333 MICKY MOUSE 222 444 666
    Where I want them to be in the follwing arrays as an example.
    String name[1] = ADAM
    String surname[1] = SANDLER
    String home[1] = 111
    String work[1] = 222
    String cell[1] = 333
    String name[2] = MICKY
    String surname[2] = MOUSE
    String home[2] = 222
    String work[2] = 444
    String cell[2] = 666
    Here is my code.
         Filename:     ContactsListInterface.java
         Date:           16 March 2008
         Programmer:     Yucca Nel
         Purpose:     Provides a GUI for entering names and contact numbers into a telephone directory.
                        Also allows options for searching for a specific name and deleting of data from the record
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class ContactsListInterface extends JFrame implements ActionListener
    { //start of class
         // Declare outputstream and inputStream
         DataOutputStream output;
         DataInputStream input;
         String filename = "phonebook";
         // construct fields, buttons, labels and text boxes
         JTextPane displayPane = new JTextPane();
         JLabel listOfContacts = new JLabel("List Of Contacts");               // creates a label for the scrollpane
         JButton createButton = new JButton("Create");
         JButton searchButton = new JButton("Search");
         JButton modifyButton = new JButton("Modify");
         JButton deleteButton = new JButton("Delete");
         // declare data arrays for name, surname, work number, home number and cell number
         private String name[] = {""};
         private String surname[] = {""};
         private String home[] = {""};
         private String work[] = {""};
         private String cell[] = {""};
         // create an instance of the ContactsListInterface
         public ContactsListInterface()
         { // start of cli()
              super("Phonebook Interface");
         } // end of cli()
         public JMenuBar createMenuBar()
         { // start of the createMenuBar()
              // construct and populate a menu bar
              JMenuBar mnuBar = new JMenuBar();                    // creates a menu bar
              setJMenuBar(mnuBar);
              JMenu mnuFile = new JMenu("File",true);               // creates a file menu in the menu bar which is visible
                   mnuFile.setMnemonic(KeyEvent.VK_F);
                   mnuFile.setDisplayedMnemonicIndex(0);
                   mnuFile.setToolTipText("File Options");
                   mnuBar.add(mnuFile);
              JMenuItem mnuFileExit = new JMenuItem("Exit");     // creates an exit option in the file menu
                   mnuFileExit.setMnemonic(KeyEvent.VK_X);
                   mnuFileExit.setDisplayedMnemonicIndex(1);
                   mnuFileExit.setToolTipText("Close Application");
                   mnuFile.add(mnuFileExit);
                   mnuFileExit.setActionCommand("Exit");
                   mnuFileExit.addActionListener(this);
              JMenu mnuEdit = new JMenu("Edit",true);               // creates a menu for editing options
                   mnuEdit.setMnemonic(KeyEvent.VK_E);
                   mnuEdit.setDisplayedMnemonicIndex(0);
                   mnuEdit.setToolTipText("Edit Options");
                   mnuBar.add(mnuEdit);
              JMenu mnuEditSort = new JMenu("Sort",true);          // creates an option for sorting entries
                   mnuEditSort.setMnemonic(KeyEvent.VK_S);
                   mnuEditSort.setDisplayedMnemonicIndex(0);
                   mnuEdit.add(mnuEditSort);
              JMenuItem mnuEditSortByName = new JMenuItem("Sort By Name");          // to sort entries by name
                   mnuEditSortByName.setMnemonic(KeyEvent.VK_N);
                   mnuEditSortByName.setDisplayedMnemonicIndex(8);
                   mnuEditSortByName.setToolTipText("Sort entries by first name");
                   mnuEditSortByName.setActionCommand("Name");
                   mnuEditSortByName.addActionListener(this);
                   mnuEditSort.add(mnuEditSortByName);
              JMenuItem mnuEditSortBySurname = new JMenuItem("Sort By Surname");     // to sort entries by surname
                   mnuEditSortBySurname.setMnemonic(KeyEvent.VK_R);
                   mnuEditSortBySurname.setDisplayedMnemonicIndex(10);
                   mnuEditSortBySurname.setToolTipText("Sort entries by surname");
                   mnuEditSortBySurname.setActionCommand("Surname");
                   mnuEditSortBySurname.addActionListener(this);
                   mnuEditSort.add(mnuEditSortBySurname);
              JMenu mnuHelp = new JMenu("Help",true);                    // creates a menu for help options
                   mnuHelp.setMnemonic(KeyEvent.VK_H);
                   mnuHelp.setDisplayedMnemonicIndex(0);
                   mnuHelp.setToolTipText("Help options");
                   mnuBar.add(mnuHelp);
              JMenuItem mnuHelpHelp = new JMenuItem("Help");          // creates a help option for help topic
                   mnuHelpHelp.setMnemonic(KeyEvent.VK_P);
                   mnuHelpHelp.setDisplayedMnemonicIndex(3);
                   mnuHelpHelp.setToolTipText("Help Topic");
                   mnuHelpHelp.setActionCommand("Help");
                   mnuHelpHelp.addActionListener(this);
                   mnuHelp.add(mnuHelpHelp);
              JMenuItem mnuHelpAbout = new JMenuItem("About");     // creates a about option for info about api
                   mnuHelpAbout.setMnemonic(KeyEvent.VK_T);
                   mnuHelpAbout.setDisplayedMnemonicIndex(4);
                   mnuHelpAbout.setToolTipText("About this program");
                   mnuHelpAbout.setActionCommand("About");
                   mnuHelpAbout.addActionListener(this);
                   mnuHelp.add(mnuHelpAbout);
              return mnuBar;
         } // end of the createMenuBar()
         // create the content pane
         public Container createContentPane()
         { // start of createContentPane()
              // try blocks for the input and output
              try
                   output = new DataOutputStream(new FileOutputStream(filename));
              catch(IOException io)
                   JOptionPane.showMessageDialog(null,"This program could not create a storage location. Please check the disk drive and the tun the program again.","Error",JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              //construct and populate panels and content pane
              JPanel labelPanel = new JPanel(); // panel is only used to put the label for the textpane in
                   labelPanel.setLayout(new FlowLayout());
                   labelPanel.add(listOfContacts);
              JPanel displayPanel = new JPanel();// panel is used to display all the contacts and thier numbers
                   setTabsAndStyles(displayPane);
                   displayPane = addTextToTextPane();
                   displayPane.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(displayPane);
                   scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // pane is scrollable vertically
                   scrollPane.setWheelScrollingEnabled(true);// pane is scrollable by use of the mouse wheel
                   scrollPane.setPreferredSize(new Dimension(400,320));
              displayPanel.add(scrollPane);
              JPanel workPanel = new JPanel();// panel is used to enter, edit and delete data
                   workPanel.setLayout(new FlowLayout());
                   workPanel.add(createButton);
                        createButton.setToolTipText("Create a new entry");
                        createButton.addActionListener(this);
                   workPanel.add(searchButton);
                        searchButton.setToolTipText("Search for an entry by name number or surname");
                        searchButton.addActionListener(this);
                   workPanel.add(modifyButton);
                        modifyButton.setToolTipText("Modify an existing entry");
                        modifyButton.addActionListener(this);
                   workPanel.add(deleteButton);
                        deleteButton.setToolTipText("Delete an existing entry");
                        deleteButton.addActionListener(this);
              labelPanel.setBackground(Color.red);
              displayPanel.setBackground(Color.red);
              workPanel.setBackground(Color.red);
              // create container and set attributes
              Container c = getContentPane();
                   c.setLayout(new BorderLayout(30,30));
                   c.add(labelPanel,BorderLayout.NORTH);
                   c.add(displayPanel,BorderLayout.CENTER);
                   c.add(workPanel,BorderLayout.SOUTH);
                   c.setBackground(Color.red);
              // add a listener for the window closing and save
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             int answer = JOptionPane.showConfirmDialog(null,"Are you sure you would like to save all changes and exit?","File submission",JOptionPane.YES_NO_OPTION);
                             if(answer == JOptionPane.YES_OPTION)
                                  save();
                                  System.exit(0);
              return c;
         } // end of createContentPane()
         protected void setTabsAndStyles(JTextPane displayPane)
         { // Start of setTabsAndStyles()
              // set Font style
              Style fontStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
              Style regular = displayPane.addStyle("regular", fontStyle);
              StyleConstants.setFontFamily(fontStyle, "SansSerif");
              Style s = displayPane.addStyle("bold", regular);
              StyleConstants.setBold(s,true);
         } // End of setTabsAndStyles()
         public JTextPane addTextToTextPane()
         { // start of addTextToTextPane()
              try
                   input = new DataInputStream(new FileInputStream(filename));
                   for(int i=0; i<name.length;i++)
                        name[i] = input.readUTF();
                        surname[i] = input.readUTF();
                        home[i] = input.readUTF();
                        work[i] = input.readUTF();
                        cell[i] = input.readUTF();
              catch(IOException io)
              Document doc = displayPane.getDocument();
              try
              { // start of tryblock
                   // clear previous text
                   doc.remove(0,doc.getLength());
                   // insert titles of columns
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   // insert data
                   for(int i=0; i<name.length; i++)
                        doc.insertString(doc.getLength(), name[i] +"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), surname[i] +"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), home[i]+"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), work[i]+"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), cell[i]+"\t",displayPane.getStyle("regular"));
              } // end of try block
              catch(BadLocationException ble)
              { // start of ble exception handler
                   System.err.println("Could not insert text.");
              } // end of ble exception handler
              return displayPane;
         } // end of addTextToTextPane()
         // code to process user clicks
         public void actionPerformed(ActionEvent e)
         { // start of actionPerformed()
              String arg = e.getActionCommand();
              // user clicks exit option
              if(arg.equals("Exit"))
                   int answer = JOptionPane.showConfirmDialog(null,"Exiting will save all changes to file. \nAre you sure you would like to save and exit now?","File submission",JOptionPane.YES_NO_OPTION);
                   if(answer == JOptionPane.YES_OPTION)
                        save();
                        System.exit(1);
              // user clicks help option
              if(arg.equals("Help"))
                   JOptionPane.showMessageDialog(null, "Welcome to the phone book application. To add a new entry press the \"Create\" button.\n To search for an entry press the \"Search\" button.\n To modify an existing entry press the \"Modify\" button. \n To delete an entry press the \"Delete\" button.","Help Topic",JOptionPane.INFORMATION_MESSAGE);
              // user clicks about option
              if(arg.equals("About"))
                   JOptionPane.showMessageDialog(null,"Phonebook v 1.01 created by Yucca Nel.\nNo copyright exists.\nThis program is freeware and should not be sold.\nEnjoy :-)","About phonebook",JOptionPane.INFORMATION_MESSAGE);
              // user clicks create button
              if(arg.equals("Create"))
                   createNew();
              // user clicks search button
              if(arg.equals("Search"))
                   searchForName(arg, name);                    // Only possible to search by name as all contacts Must have a name
              if(arg.equals("Modify"))
                   modifyContact(arg,name);
                   save();
              // user clicks the sort by name option
              if(arg.equals("Name"))
                   sort(name);
              if(arg.equals("Surname"))
                   sort(surname);
         } // end of actionPerformed()
         // Method to ceate a new entry
         public void createNew()
         { // start of createNew()
              int newHome, newWork, newCell = 0;
              String newContactName = JOptionPane.showInputDialog(null,"Please enter the new contacts first name or press cancel to exit.");
              if(newContactName == null)     finish();                         // if user clicks cancel
              if(newContactName.length() <=0)
                   JOptionPane.showMessageDialog(null,"You did not enter a valid name.\nPlease make sure you enter data correctly.","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();                                                  // To return to the create method
              String newContactSurname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname or press cancel to exit.");
              if(newContactSurname == null)     finish();                    // if user clicks cancel
              if(newContactSurname.equals(""))
                   int answer = JOptionPane.showConfirmDialog(null,"You did not enter a surname.\nAre you sure you wish to leave the surname empty?","No data entered",JOptionPane.YES_NO_OPTION);   // Asks if data was valid
                   if(answer == JOptionPane.NO_OPTION)
                        newContactSurname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname.");
              String newContactWorkNum = JOptionPane.showInputDialog(null,"Please enter the new contacts work number or press cancel to exit.");
              if(newContactWorkNum == null)   finish();                    // if user clicks cancel
              String newContactHomeNum = JOptionPane.showInputDialog(null,"Please enter the new contacts home number or press cancel to exit.");
              if(newContactHomeNum == null)     finish();                    // if user clicks cancel
              String newContactCellNum = JOptionPane.showInputDialog(null,"Please enter the new contacts cell number or press cancel to exit.");
              if(newContactCellNum == null)     finish();                    // if user clicks cancel
              // enlarge the arrays so they can accept data
              name = enlargeArray(name);
              surname = enlargeArray(surname);
              work = enlargeArray(work);
              home = enlargeArray(home);
              cell = enlargeArray(cell);
              // add the new data into the arrays
              name[name.length-1] = newContactName;
              surname[surname.length-1] = newContactSurname;
              home[home.length-1] = newContactHomeNum;
              work[work.length-1] = newContactWorkNum;
              cell[cell.length-1] = newContactCellNum;
              // sort the names so they appear in alphebetical order
              sort(name);
         } // end of createNew()
         // The enlarge array method
         //method to enlarge an array by 1
         public String[] enlargeArray(String[] currentArray)
              String[] newArray = new String[currentArray.length + 1];
              for (int i = 0; i < currentArray.length; i++)
              newArray[i] = currentArray;
              return newArray;
         }// End of enlargeArray()
         // The Sort Method
         public void sort(String tempArray[])
         { // start of sort()
              // for loop
              for(int pass = 1; pass < tempArray.length; pass++)
                   for(int element = 0; element < tempArray.length -1; element++)
                   if(tempArray[element].compareTo(tempArray[element+1])>0)
                        swap(name, element, element+1);
                        swap(surname, element, element+1);
                        swap(home, element, element+1);
                        swap(work, element, element+1);
                        swap(cell, element, element+1);
              addTextToTextPane();
         } // end of sort()
         // The swap method
         public void swap(String swapArray[], int first, int second)
         { // start of swap()
              String hold;
              hold = swapArray[first];
              swapArray[first] = swapArray[second];
              swapArray[second] = hold;
         } // end of swap()
         // method to search for a name
         public void searchForName(String searchField, String searchArray[])
         { // start of searchForName()
              try
                   Document doc = displayPane.getDocument();                         // assign text to an object
                   doc.remove(0,doc.getLength());                                        // clear the screen
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   String searchValue = JOptionPane.showInputDialog(null,"Please enter the 1st name of the person you would like to see phone numbers for or press cancel to exit.");
                   boolean found = false;
                   if(searchValue == null) finish();                                   // if user clicks cancel
                   //search the array
                   for(int i=0; i < name.length; i++)
                        if(searchValue.compareTo(searchArray[i])==0)
                             doc.insertString(doc.getLength(), name[i] +"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), surname[i] +"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), home[i]+"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), work[i]+"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), cell[i]+"\t",displayPane.getStyle("regular"));
                             found = true;
                   if(found == false)
                        JOptionPane.showMessageDialog(null,"No contact with that name found.","No result found",JOptionPane.INFORMATION_MESSAGE);
                        sort(name);
              catch(BadLocationException ble)
                   System.err.println("Could not insert text.");
         } // end of searchForName()
         // Method to modify contact
         public void modifyContact(String searchField, String searchArray[])
         { // start of modifyContact()
              try
                   Document doc = displayPane.getDocument();                         // assign text to an object
                   doc.remove(0,doc.getLength());                                        // clear the screen
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   String modifyValue = JOptionPane.showInputDialog(null,"Please enter the 1st name of the person you would like to change details for. Or press cancel to exit");
                   boolean found = false;
                   if(modifyValue == null)      finish();                              // if user clicks cancel
                   //search the array
                   for(int i=0; i < name.length; i++)
                        if(modifyValue.compareTo(searchArray[i])==0)
                             // To change the name
                             String oldName = name[i];
                             String newName = JOptionPane.showInputDialog(null,"Please enter a new name if you would like to change the name for "+name[i]+". Or press cancel to exit");
                             if(newName == null)
                                  name[i] = oldName;                                        // if user clicks cancel keep old entry
                                  finish();
                             if(newName.equals(""))                                        // if no data entered then name will stay same
                                  JOptionPane.showMessageDialog(null,"You did not enter a name in the name field.\nOld name will be kept.","Information Message",JOptionPane.INFORMATION_MESSAGE);
                                  name[i] = oldName;
                                  addTextToTextPane();
                             else
                                  name[i] = newName;                                        // new name is saved into array
                                  addTextToTextPane();
                             //To change the surname
                             String oldSurname = surname[i];
                             String newSurname = JOptionPane.showInputDialog(null,"Please enter a new surname if you would like to change the surname for "+name[i]+". Or press cancel to exit");
                             if(newSurname == null)
                                  surname[i] = oldSurname;                              // if user clicks cancel keep old entry
                                  finish();
                             if((oldSurname.length()>0) && newSurname.length()<=0)          // if surname existed but no new surname was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the surname for "+name[i]+".\nAre you sure you would like to remove the surname for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old surname and leave no surname in place
                                       surname[i] = newSurname;                         // new surname is saved into the array
                                  else                                                       // user does not wish to remove surname
                                       surname[i] = oldSurname;                         // keep the old surname
                             else                                                            // just replace the surname with new one as everything seems fine
                                  surname[i] = newSurname;
                             //To change the work number of contact
                             String oldWork = work[i];
                             String newWork = JOptionPane.showInputDialog(null,"Please enter a new work number if you would like to change the work number for "+name[i]+". Or press cancel to exit");
                             if(newWork == null)
                                  work[i] = oldWork;                                        // user clicks cancel keep old entry
                                  finish();
                             if((oldWork.length()>0) && newWork.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the work number for "+name[i]+".\nAre you sure you would like to remove the work number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       work[i] = newWork;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       work[i] = oldWork;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  work[i] = newWork;
                             //To change the work number of contact
                             String oldHome = home[i];
                             String newHome = JOptionPane.showInputDialog(null,"Please enter a new home number if you would like to change the home number for "+name[i]+". Or press cancel to exit");
                             if(newHome == null)
                                  home[i] = oldHome;                                        // if user clicks cancel keep old value
                                  finish();
                             if((oldHome.length()>0) && newHome.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the home number for "+name[i]+".\nAre you sure you would like to remove the home number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       home[i] = newHome;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       home[i] = oldHome;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  home[i] = newHome;
                             //To change the cell number
                             String oldCell = cell[i];
                             String newCell = JOptionPane.showInputDialog(null,"Please enter a new cell number if you would like to change the cell number for "+name[i]+". Or press cancel to exit");
                             if(newCell == null)
                                  cell[i] = oldCell;                                        // if user clicks cancel keep old value
                                  finish();
                             if((oldCell.length()>0) && newCell.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the Cell number for "+name[i]+".\nAre you sure you would like to remove the cell number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       cell[i] = newCell;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       cell[i] = oldCell;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  cell[i] = newCell;
                             found = true;
                        addTextToTextPane();
                   if(found == false)
                        JOptionPane.showMessageDialog(null,"No contact with that name found.","No result found",JOptionPane.INFORMATION_MESSAGE);
                        sort(name);
                        addTextToTextPane();
              catch(BadLocationException ble)
                   System.err.println("Could not insert text.");
         } // end of searchForName()
         // finish method for cancel button
         public void finish()
              JOptionPane.showMessageDialog(null,"This program will now close and automatically save all data entered. You may restart the program to modify any changes.","Information Message",JOptionPane.INFORMATION_MESSAGE);
              System.exit(0);
         // method to save data to file
         public void save()
              try
                   for(int i=0; i < name.length; i++)
                        output.writeUTF(name[i]);
                        output.writeUTF(surname[i]);
                        output.writeUTF(work[i]);
                        output.writeUTF(home[i]);
                        output.writeUTF(cell[i]);
                   JOptionPane.showMessageDialog(null,"Data succesfully saved to file.","Information message",JOptionPane.INFORMATION_MESSAGE);
              catch(IOException io)
                   System.exit(1);
         public static void main(String[] args)
         { // start of main()
              // Set look and feel of interface
              try
              { // start of try block
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } // end of try block
              catch(Exception e)
              { // start of catch block
                   JOptionPane.showMessageDialog(null,"There was an error in setting the look and feel of this application","Error",JOptionPane.INFORMATION_MESSAGE);
              } // end of catch block
              ContactsListInterface cli = new ContactsListInterface();
              cli.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              cli.setJMenuBar(cli.createMenuBar());
              cli.setContentPane(cli.createContentPane());
              cli.setSize(520,500);
              cli.setVisible(true);
              cli.setResizable(false);
         } // end of main()
    } //end of classBefore thinking I am lazy I dont want you to correct my code. Just give me a few pointers on how to get my arrays back from the file and how to set my strings to  a non null value that wont show when my program starts.
    Edited by: Yucca on Mar 24, 2008 7:24 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

    Yucca wrote:
    It's pretty easy to write objects to file, but it depends on what you want to do with that file. Do you want it to be a human-readable text file? Is it only to be used by your program? The file is to be used by my program to save to and to read from. But I understand now that saving each entry as a string and not writing it to an array may be easier. Do I use the buffered reader instead of InputStreamReader? Oh sorry I forgot to mention that the file I save to will later be used when I convert my application to a database type/SQL tyype aplication.
    Edited by: Yucca on Mar 24, 2008 8:06 PMIt sounds to me like object serialization would be the easiest for what you want to do. Read through this:
    http://java.sun.com/developer/technicalArticles/Programming/serialization/
    And these apis:
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectOutputStream.html
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectInputStream.html

  • Use ComboBox TableCellEditor  - values are not saved to the table model

    Hi,
    I got a combobox cell editor that uses to edit one of the columns.
    And i got an ok button that uses to collect the data from the table and save it to the db.
    In case i started editing of a cell and the editor is still displayed- if i will click on the button the data that will be colected from the table model will not contained the updated value in the cell editor.
    In this case the user think his changes were saved but the last updated field is not updated.
    Is this a bug i got in the cell editor or this is the normal behaviour?
    Can it be fixed? (So that if the cell is in the middle of editing the value that will be saved is the last value that was selected).
    public class PriorityCellEditor extends StandardComboBox implements TableCellEditor {
        private boolean isEditMode=false;
         * A list of eventlisteners to call when an event is fired
        private EventListenerList listenerList = new EventListenerList();
         * the table model
        public StbAreaClusterPriorityCellEditor(boolean isEditMode) {
            super(StbAreaMapper.clustersPriorities);
            setEditMode(isEditMode);
            setEditable(false);
            this.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            setAlignmentX(Component.LEFT_ALIGNMENT);
        public boolean isEditMode() {
            return isEditMode;
        public void setEditMode(boolean editMode) {
            isEditMode = editMode;
            setEnabled(editMode);
        public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelecte, int row, int column) {
            int selectedIndex;
            if (isSelecte) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            if(value instanceof String){
                selectedIndex=StbAreaMapper.mapGuiPriorityDescToGuiCode((String)value);
                setSelectedIndex(selectedIndex);
            return this;
        public void cancelCellEditing() {
            fireEditingCanceled();
        public Object getCellEditorValue() {
            return getSelectedItem();
        public boolean isCellEditable(EventObject anEvent) {
            return isEditMode;
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        public boolean stopCellEditing() {
            fireEditingStopped();
            return true;
         * Adds a new cellEditorListener to this cellEditor
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);
         * Removes a cellEditorListener from this cellEditor
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingStopped(
                            new ChangeEvent(this));
         * Notify all listeners that have registered interest for notification on
         * this event type.
         * @see javax.swing.event.EventListenerList
        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this));
    }

    Try this
    yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

Maybe you are looking for