Link to home
Start Free TrialLog in
Avatar of gbcbr
gbcbrFlag for Cyprus

asked on

Setting text into JTextField by typing

Please advice how to set text value into JTextField by typing on it?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

What's the problem? It should worked unless setEnabled(false) has been called on it
(if it didn't have focus you wouldn't be typing on it)
Avatar of gbcbr

ASKER

Now I have:
support_EURUSD.setPreferredSize(new Dimension(80, 30));
        support_EURUSD.setBackground(new Color(255, 132, 132));
        support_EURUSD.setHorizontalAlignment(JTextField.CENTER);
        support_EURUSD.setText("1.3924"); // Support level
        support_EURUSD.setFont(new Font("Lucida Grande", 0, 12));

Open in new window

What I have to add to set text from GUI
Avatar of gbcbr

ASKER

I can type, but restart app return old value. I want to change value setText("1.3924") and keep it
>         support_EURUSD.setText("1.3924"); // Support level

that line will set the text of your text field

if you need to change it then just call setText() again to change it
> I can type, but restart app return old value. I want to change value setText("1.3924") and keep it

then you need to store that value somewhere, and then set it using that stored value

        support_EURUSD.setText(storedValue); // Support level

Avatar of gbcbr

ASKER

>>then you need to store that value somewhere, and then set it using that stored value
How to store it?
database, properties file, preferences, ... many options :)
Avatar of gbcbr

ASKER

So, it is no Action listener for typing?
Avatar of gbcbr

ASKER

Anyway I don't understand how I can type new value in GUI text field and this value will be saved somewhere, which method will manage reading from this field and saving in properties file?
JTextField will not save this value between program runs.
You will need to do this yourself.

How you store this value is going to be specific to your application.
Avatar of gbcbr

ASKER

>>  is going to be specific to your application.
what you mean - specific?
It's the common, standard case, I just type value into text field and for me doesn't matter in which way to save it.
I don't understand who listen my typing. If I understand this I can, build some logic from this point.
For example:
When I press button I have:
chartButton_EURUSD.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    try {
                        jToggleButton3_mouseClicked(e);
                    } catch (Exception f) {
                        f.printStackTrace();
                    }
                }

Open in new window

and I can create procedure what to do, but for typing I have no idea how to manage it.
The best way is to add a JButton next to the text field, the user enters text and clicks the button, and in the button ActionListener you do something with the text.

You can also add an ActionListener to the JTextField, but it will not get called UNLESS the user presses the Enter key.  This is probably not obvious enough, I would add the JButton instead.
Avatar of gbcbr

ASKER

I don't think that to add button for me is good solution.
I have JFrame with 10 JPanels in rows with 15 elements each, 5 of them have to be editable by typing, so I have to add 50 JButtons?
It will destroy my working panel, because now all elements are informative, and this 50 buttons will sit there just for pishing 3 times a day.
Avatar of gbcbr

ASKER

May be possible to create one button SAVE and connect all JTextFields to this button?
You can certainly do that, yes.  Whatever works best for your application.
Avatar of gbcbr

ASKER

So, it's some other ideas about this question.
In general, I don't need to save values in properties file during application work, I need to save them when I exit.
But stil I have no idea how to get value from these textfields, some method has to read them and set them into properties file and after set them back.
There is no automatic way to save the value in a textfield and restore it when you exit the program.  You will have to write this yourself.

To simply get the text value from a textfield, call textfield.getText().  This will return a String with the value of the text field.
Avatar of gbcbr

ASKER

>> call textfield.getText().
I'm already have these 50 return methods which return values of this 50 text fields.
How to write them in property file?
Avatar of gbcbr

ASKER

I read it yesterday, it's just common information, I need advice for my specific case.
Would this be an auto-save or an explicit one?
Avatar of gbcbr

ASKER

I prefer auto-save on exit.
Avatar of gbcbr

ASKER

Somewhere here:
menuFileExit.setText("Exit");
        menuFileExit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    fileExit_ActionPerformed();
                }
            });
.....................
void fileExit_ActionPerformed() {
        mFxcmGateway.logout();
        System.exit(0);
    }

Open in new window

SOLUTION
Avatar of rodness
rodness
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ps-  The advantage of doing this on the WindowListener instead of in the menu command is that if they click the window close button (instead of using the menu exit) is that you will still save the data.
>>I prefer auto-save on exit.

Use the following with Rodness' WindowListener. Give all your text fields unique names
private void saveFields(Container contentPane){
	for (Component c : contentPane.getComponents()) {
	    if(c instanceof Container) {
		saveFields((Container)c);
	    }
	    if (c instanceof JTextField) {
		JTextField tf = (JTextField)c;
		System.out.println(tf.getText()); // Uncomment next line in real one
		//props.setProperty(tf.getName(), tf.getText());
	    }
	}
    }

Open in new window

Avatar of gbcbr

ASKER

So, as I understood it should be something like this:
 
Properties prop = new Properties();
OutputStream out = new FileOutputStream("my.properties");
.............

private void jbInit() throws Exception {

jFrame.addWindowListener( new WindowAdapter() {

      @Override
      public void windowClosing(WindowEvent e) {
try {
     prop.setProperty("resistGBPCHF", "??????????????");
     prop.store(out, null);
} catch (IOException ex) {
     ex.printStackTrace();
} finally {
     out.close();
}


      }
});

.................

    public String getTextresistGBPCHF() {
        String resist = resistance_GBPCHF.getText();
        //        System.out.println("    DCC  resist = " + resist);
        return resist;
    }

Open in new window

But how to set value "resist"?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gbcbr

ASKER

OK, now little bit warmer:)
It might be actually simpler to serialize the whole panel containing the fields
Avatar of gbcbr

ASKER

@objects
I try to follow your sample, but I have error messages at addWindowListener - method addWindowListener not found and
 out.close(); - IOException not handled
import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.IOException;

.............

public class DCC extends JFrame {

..............

private void jbInit() throws Exception {

..............

        this.getContentPane().addWindowListener(new WindowAdapter() {

                Properties prop = new Properties();
                OutputStream out = new FileOutputStream("dcc.properties");

                @Override
                public void windowClosing(WindowEvent e) {
                    try {
                        prop.setProperty("resistance_EURUSD", "eurusd_resist");
                        prop.store(out, null);
                      } catch (IOException ex) {
                          ex.printStackTrace();
                        
                    } finally {
                        out.close();                        
                      }                       
                }
            });
..................

        resistance_EURUSD.setPreferredSize(new Dimension(80, 30));
        resistance_EURUSD.setBackground(new Color(181, 255, 181));
        resistance_EURUSD.setHorizontalAlignment(JTextField.CENTER);
 //       resistance_EURUSD.setText("1.4027"); // Resistanse level
        resistance_EURUSD.setFont(new Font("Lucida Grande", 0, 12));
        resistance_EURUSD.setName("resistance_EURUSD");

.................

    public String getTextresistEURUSD() {
        String eurusd_resist = resistance_EURUSD.getText();
        //        System.out.println("    DCC  resist = " + resist);
        return eurusd_resist;
    }

Open in new window

Avatar of gbcbr

ASKER

@CEHG
>>simpler to serialize the whole panel

I don't know about this way, can you advice please?
Essentially it'd be

contentPane = (JPanel)oin.readObject();
setContentPane(contentPane);

at startup and

oout.writeObject(contentPane);

at close
Avatar of gbcbr

ASKER

@CEHJ
but where it will save it at close, it has to be some file.
Yes, into a file
Avatar of gbcbr

ASKER

in dcc.properties?
No, it wouldn't be a properties file, but a serialization one, say 'gui.ser'

http://www.tutorialspoint.com/java/java_serialization.htm
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you might also want to look at the Preferences API
http://www.vogella.de/articles/JavaPreferences/article.html
makes things a little simpler in some ways
Here's a way with serialization. Run it, type into it, close it, reopen it:
import java.awt.*;
import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;


public class GuiSaver extends JFrame {
    final static String SERIALIZATION_FILE = "gui.ser";
    private JPanel gui;
    private JTextField tf;

    private JPanel makeGui() {
        gui = null;

        File f = new File(SERIALIZATION_FILE);

        if (f.exists()) {
            ObjectInputStream in = null;

            try {
                in = new ObjectInputStream(new FileInputStream(f));
                gui = (JPanel) in.readObject();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (Exception e) { /* ignore */
                }
            }
        } else {
            gui = new JPanel();
            tf = new JTextField(10);
            gui.add(tf);
        }

        return gui;
    }

    private void setGui() {
        try {
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	    addWindowListener(new Persister());
            setContentPane(makeGui());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class Persister extends WindowAdapter {
	public void windowClosing(WindowEvent ev) {
	    persistGui();
	    System.exit(0);
	}
    }


    private void persistGui() {
        File f = new File(SERIALIZATION_FILE);

        ObjectOutputStream out = null;

        try {
            out = new ObjectOutputStream(new FileOutputStream(f));
            out.writeObject(gui);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) { /* ignore */
            }
        }
    }

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        GuiSaver f = new GuiSaver();
                        f.setGui();
                        f.setSize(200, 200);
                        f.setVisible(true);
                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Open in new window

Avatar of gbcbr

ASKER

@CEHJ
Sorry for the delay, it's not me, it's Japanese tsunami destroy whole market. So, it was no time for non-critical questions. I needed to arrange much critical questions.
Anyway, please explain me about GuiSaver class, how I can use it and how to connect to it my data?
It has a main method, means it works alone, but in my case it has to be integrated into my app.
Avatar of gbcbr

ASKER

@objects
Please accept the same excuse for delay.
I have this errors:
addWindowListener - method addWindowListener not found; Presist1.tiff
>>
Anyway, please explain me about GuiSaver class, how I can use it and how to connect to it my data?
It has a main method, means it works alone, but in my case it has to be integrated into my app.
>>

It's just a demo to show what you should do with your own code. You need to serialize the panel that holds all the fields you're interested in persisting
Did you run the demo btw?
you need to add the window listener to the frame, not the content pane
just use:

addWindowListener(new WindowAdapter() ......
Avatar of gbcbr

ASKER

@CEHJ
I run the demo, looks nice, but it's need for me some time to understand how to serialize my panel.
Avatar of gbcbr

ASKER

@objects
I integrate, compile and run this code, as I see it's only OutputStream which record file, but how to read and restore data?
 
private void jbInit() throws Exception {

      this.addWindowListener(new WindowAdapter() {
      
              Properties prop = new Properties();
              OutputStream out = new FileOutputStream("dcc.properties");

       @Override
      
              public void windowClosing(WindowEvent e) {
                  try {
                      Properties prop = new Properties();
                      OutputStream out = new FileOutputStream("dcc.properties");
                      prop.setProperty("resistance_EURUSD", "eurusd_resist");
                      prop.store(out, null);
                    } catch (IOException ex) {
                        ex.printStackTrace();
      
                  } finally {
                      try {out.close();} catch (Exception ex) {}
                    }
              }
      });

        this.setJMenuBar(menuBar);
        this.getContentPane().setLayout(null);

Open in new window

It has to be InputStream also, please advice how to locate it also?
you just need to do the reverse ie. open the property file and read the values from it
http://download.oracle.com/javase/tutorial/essential/environment/properties.html
Avatar of gbcbr

ASKER

I check now dcc.properties, but it's empty.
Nothing written in. ?
private void jbInit() throws Exception {

        Properties defaultProps = new Properties();
        FileInputStream in = new FileInputStream("fxmsg.properties");
        defaultProps.load(in);
        in.close();

        Properties applicationProps = new Properties(defaultProps);

        in = new FileInputStream("dcc.properties");
        applicationProps.load(in);
        in.close();

      this.addWindowListener(new WindowAdapter() {
      
              Properties prop = new Properties();
              OutputStream out = new FileOutputStream("dcc.properties");

       @Override
      
              public void windowClosing(WindowEvent e) {
                  try {
                      Properties prop = new Properties();
                      OutputStream out = new FileOutputStream("dcc.properties");
                      prop.setProperty("resistance_EURUSD", "eurusd_resist");
                      prop.store(out, null);
                    } catch (IOException ex) {
                        ex.printStackTrace();
      
                  } finally {
                      try {out.close();} catch (Exception ex) {}
                    }
              }
      });

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gbcbr

ASKER

Anyway it's still empty.
I don't understand why it doesn't write at least resistance_EURUSD=,  maybe I have to clarify better value of field, but field name it's ok.
Maybe it doesn't see this dcc.properties file?
How I can check if it's visible or not?
make sure you're checking the right directory
it would throw an exception if it wasn't working
Avatar of gbcbr

ASKER

I have only one file with this name here, this what I was asking before: is it a right place where is located? DCC-pr.tiff
you're code would be looking/creting the file in the same directory as you are running it from
Avatar of gbcbr

ASKER

>>it would throw an exception if it wasn't working
I change name:
out = new FileOutputStream("dcc1.properties");

Open in new window

but it's no any exception was thrown and I can't find anywhere new created file with this name
Avatar of gbcbr

ASKER

OK, I make  
Properties prop = new Properties();
              OutputStream out = new FileOutputStream("dcc1.properties");

       @Override
      
              public void windowClosing(WindowEvent e) {
                    OutputStream out = null;
           
                  try {
                      Properties prop = new Properties();
                      out = new FileOutputStream("dcc1.properties");

Open in new window

and it create new file at the same place but it's also empty
DCC-pr1.tiff
why do you create out and prop twice? thats just going to cause you problems.
Avatar of gbcbr

ASKER

I delete them but file still is empty
this.addWindowListener(new WindowAdapter() {

       @Override
      
              public void windowClosing(WindowEvent e) {
                    OutputStream out = null;
           
                  try {
                      Properties prop = new Properties();
                      out = new FileOutputStream("dcc.properties");
                      prop.setProperty("resistance_EURUSD", "eurusd_resist");
                      prop.store(out, null);
                    } catch (IOException ex) {
                        ex.printStackTrace();
      
                  } finally {
                        try {
                            if (out != null)
                                out.close();
                        } catch (Exception ex) {
                        }
                    }
              }
      });

Open in new window

Maybe something not correct here
prop.store(out, null);

Open in new window

It to be some reason why it doesn't write anything.
Please attach your gui class source
You can start by working the following into the code, calling it in windowClosing. Verify that the file gui.ser has been created
final static String SERIALIZATION_FILE = "gui.ser";

    private void persistGui() {
        File f = new File(SERIALIZATION_FILE);

        ObjectOutputStream out = null;

        try {
            out = new ObjectOutputStream(new FileOutputStream(f));
            out.writeObject(jPanel_EURUSD);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) { /* ignore */
            }
        }
    }

Open in new window

Avatar of gbcbr

ASKER

@CEHJ
Thank you for the code.
Just please clarify where exactly to place it.
I place it inside windowClosing method but it generate errors.
this.addWindowListener(new WindowAdapter() {

       @Override      
              public void windowClosing(WindowEvent e) {
                   
                private void persistGui() {
                    
                        File f = new File(SERIALIZATION_FILE);

                        ObjectOutputStream out = null;

                        try {
                            out = new ObjectOutputStream(new FileOutputStream(f));
                            out.writeObject(jPanel_EURUSD);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                out.close();
                            } catch (Exception e) { /* ignore */
                            }
                        }
                    }

Open in new window

Method persistGUI not used;
Type file  not found;
Type ObjectOutputStream not found and other.
For sure I place it wrong.
Please advice.
You've nested methods. windowClosing and persistGui should be separate, the former calling the latter
Also

import java.io.*;

in your code or just the io classes required
Avatar of gbcbr

ASKER

I start and close app but file gui.ser was not created
I'm assuming no compilation errors, so please attach new DCC.java
changing how you save it isn't going to fixs your problem.

If the files not being created then that would suggest the code is not getting called. Add some debug to check it is called
Avatar of gbcbr

ASKER

@objects
You are right, it doesn't call anything in windowClosing method
this.addWindowListener(new WindowAdapter() {

//       @Override
      
              public void windowClosing(WindowEvent e) {

                    System.out.println(" windowClosing = " + e);
           
                         persistGui();
              }
           
//                    OutputStream out = null;
                    
                private void persistGui() {
                    
                        File f = new File(SERIALIZATION_FILE);

                    System.out.println(" File = " + f);

                        ObjectOutputStream out = null;

                        try {
                            out = new ObjectOutputStream(new FileOutputStream(f));

                        System.out.println(" ObjectOutputStream = " + out);
                            
                            out.writeObject(jPanel_EURUSD);
                        } catch (Exception e) {
                            e.printStackTrace();

Open in new window

You're not calling System.exit(0); after persistGui(); so i'm surprised you managed to close the window at all. The file gui.ser will be in the same directory from which you run the app
Avatar of gbcbr

ASKER

I call  System.exit(0);
from
menuFileExit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    fileExit_ActionPerformed();
                }
            }); 

void fileExit_ActionPerformed() {
        mFxcmGateway.logout();
        System.exit(0);
    }

Open in new window

why I have to call it second time?
If you call it there your WindowListener won't get called. You need to call dispose on the gui window (DCC.this.dispose();)
Or more easily (and this is why persistGui should be a method *of your gui* (not the WindowListener))
void fileExit_ActionPerformed() {
        mFxcmGateway.logout();
        persistGui();
        System.exit(0);
}

Open in new window

Avatar of gbcbr

ASKER

Now it create gui.ser
void fileExit_ActionPerformed() {
        mFxcmGateway.logout();
        persistGui();
        System.exit(0);
    }

    private void persistGui() {

        File f = new File(SERIALIZATION_FILE);

        ObjectOutputStream out = null;

        try {
            out = new ObjectOutputStream(new FileOutputStream(f));
            out.writeObject(jPanel_EURUSD);
            System.out.println(" File = " + f);
            System.out.println(" ObjectOutputStream = " + out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) { /* ignore */
            }
        }
    }

Open in new window

File = gui.ser
ObjectOutputStream = java.io.ObjectOutputStream@5d53d05b

Open in new window

but how now to call this file on the start and get information from it?
That's a little more tricky. What you need to do is study my demo carefully. You basically read jPanel_EURUSD from gui.ser if that file is present. If it's not, you construct it in the normal way
> You are right, it doesn't call anything in windowClosing method

then just fix that problem and you're done

> but how now to call this file on the start and get information from it?

you can't.
you should use a Properties file for that
Avatar of gbcbr

ASKER

@objects
>>you should use a Properties file for that
But I can't write into this file anything. It's empty and I don't understand a reason, because at my view everything was done logically.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gbcbr

ASKER

@objects
As always you are right, it was just invisible. I place it:
void fileExit_ActionPerformed() {
        mFxcmGateway.logout();
      windowClosing();
//        persistGui();
        System.exit(0);
    }

    public void windowClosing() {
        OutputStream out = null;

        try {
            Properties prop = new Properties();
            out = new FileOutputStream("dcc.properties");

            System.out.println(" FileOutputStream = " + out);

            prop.setProperty("resistance_EURUSD", "eurusd_resist");
            prop.store(out, null);
        } catch (IOException ex) {
            ex.printStackTrace();

        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (Exception ex) {
            }
        }
    }

Open in new window

and I have the result
#Wed Mar 23 12:28:26 EET 2011
resistance_EURUSD=eurusd_resist

Open in new window

but why I have name of value instead of value?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gbcbr

ASKER

Now it's fine, how to get it back now?
resistance_EURUSD.setPreferredSize(new Dimension(80, 30));
        resistance_EURUSD.setBackground(new Color(181, 255, 181));
        resistance_EURUSD.setHorizontalAlignment(JTextField.CENTER);

        resistance_EURUSD.setText(??????getProperty(eurusd_resist));

        resistance_EURUSD.setFont(new Font("Lucida Grande", 0, 12));
        resistance_EURUSD.requestFocusInWindow();
        resistance_EURUSD.setName("resistance_EURUSD");

Open in new window

>> prop.setProperty("resistance_EURUSD", eurusd_resist);

You only want to store *one* property?
Avatar of gbcbr

ASKER

@objects
I found how to get it back:
resistance_EURUSD.setText(applicationProps.getProperty("resistance_EURUSD"));

Open in new window


@CEHJ
>>You only want to store *one* property?
of course not, and your way much easy because I have only 10 JPanels, but I have to save 80 textfields, so I have big donkey job ahead. But with properties it starts to work apart of serialization. I read your sample, but I don't see how I can apply all these methods in my DCC class without destroying whole system.
>>so I have big donkey job ahead

Yes you do if you use Properties.

>> but I don't see how I can apply all these methods in my DCC class without destroying whole system.

1. write one method that returns just the base panel. Let's call it 'makeBasePanel'.
2. put all the code that currently populates jPanel_EURUSD into it
3. in your code, call it as below.

This btw is a good thing to do in any case, as it modularises your code
jPanel_EURUSD = makeBasePanel();

Open in new window

Step 2. should largely  be a cut and paste job (back up first)

Let me know when you've got that working and we'll put the final piece in place
Avatar of gbcbr

ASKER

OK, I'll try
Avatar of gbcbr

ASKER

@CEHJ
I don't want to mix these two ways in my working class.
I've reduce number of changeable fields to 20 and already complete this job.
I'll open new question about serialization job, duplicate DCC to DCC1 and we'll play with it.
Anyway, thank you for your efforts.

@objects
Thank you for your assistance, now I know how to manage Properties files.
OK :)