JTextField + I/O saving

Hello friends , i am trying to make simple project of ATM . I successfully created all my forms but now having difficulty in saving objects .
Ok i have one frame with 3 JTextField and 2 JPasswordField .. And one Continue JButton . What i am trying is when the user fills up all TextField and presses the continue button ...all data from textfield should save to a file .Well i was trying the Serializable method ..but it seems not to work .
Heres my code ..please tell me what to change or add
Hey guys i am trying to make a project on ATM .I have very basic knowledge of JAVA . I made Jframe and added some JText to it .. but i want is this when i click button , all text in JTextField and JPasswordField should be saved in a file . I am trying to use Serializable method to save object . Heres my code ...can you tell me where i am going wrong ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.io.*;
public class  Page3_NewUser implements Serializable{
     transient JFrame p3f3 = new JFrame("AKS Online ATM");
     transient JTextField p3t1,p3t2,p3t3;
     transient JPasswordField p3pp1,p3pp2;
      String Name,UserID;
      String Pass1 , Pass2 ;
      String Pin;
     public void StartF3(){
          JPanel p3p1 = new JPanel();
          JPanel p3p2 = new JPanel();
          JPanel p3p3 = new JPanel();
          JPanel p3p4 = new JPanel();
          JPanel p3p5 = new JPanel();
          JPanel p3p6 = new JPanel();
          JPanel p3p7 = new JPanel();
          JPanel p3p8 = new JPanel();
          JPanel p3p9 = new JPanel();
          JLabel p3l1 = new JLabel();// for 1st image
          JLabel p3l2 = new JLabel("Full Name:");
          JLabel p3l3 = new JLabel("User ID:");
          JLabel p3l4 = new JLabel("Password:");
          JLabel p3l5 = new JLabel("Retype Password:");
          JLabel p3l6 = new JLabel("Pin Code:");
          JLabel p3l7 = new JLabel();// for 2nd img
          //JLabel p3l9 = new JLabel("This is testing");
           p3t1 = new JTextField(15);
            p3t2 = new JTextField(15);
           p3t3 = new JTextField(15);
            p3pp1 = new JPasswordField(5);
            p3pp2 = new JPasswordField(5);
          JButton p3b1 = new JButton("Previous");
          JButton p3b2 = new JButton("Continue");
          JButton p3b3 = new JButton("Reset");
          JButton p3b4 = new JButton("Cancel");
          // Action listener
          P3_Previous a = new P3_Previous();
          p3_Continue b = new p3_Continue();
          p3b1.addActionListener(a);
          p3b2.addActionListener(b);
          p3t1.setText("Enter your name");
          p3t2.setText("Choose unique User ID");
          p3t3.setText("Enter 4 digit Pin Code");
          p3pp1.setText("1234");
          p3pp2.setText("1234");
          p3t1.setRequestFocusEnabled(true);
          p3t1.selectAll();
          p3t2.selectAll();
          p3t3.selectAll();
          p3pp1.selectAll();
          p3pp2.selectAll();
          p3f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         ImageIcon img1 = new ImageIcon("atm_banner.jpg");
         p3l1.setIcon(img1);
         p3p1.add(p3l1);
         p3p1.setBackground(Color.WHITE);
         p3p5.add(p3l2);
         p3p5.add(p3t1);
         p3p6.add(p3l3);
         p3p6.add(p3t2);
         p3p7.add(p3l4);
         p3p7.add(p3pp1);
         p3p8.add(p3l5);
         p3p8.add(p3pp2);
         p3p9.add(p3l6);
         p3p9.add(p3t3);
         p3p2.setLayout(new BoxLayout(p3p2,BoxLayout.Y_AXIS));
         p3p2.add(p3p5);
         p3p2.add(p3p6);
         p3p2.add(p3p7);
         p3p2.add(p3p8);
         p3p2.add(p3p9);
         //---- temp
         ImageIcon img2 = new ImageIcon("ID.jpg");
         p3l7.setIcon(img2);
         p3p3.add(p3l7);
         p3p3.setBackground(Color.WHITE);
         p3p4.setBackground(Color.GRAY);
         p3p4.add(new JLabel(Calendar.getInstance().getTime().toString()));
         p3p4.add(p3b1);
         p3p4.add(p3b2);
         p3p4.add(p3b3);
         p3p4.add(p3b4);
         p3f3.getContentPane().add(BorderLayout.NORTH , p3p1);
          p3f3.getContentPane().add(BorderLayout.CENTER , p3p2);
          p3f3.getContentPane().add(BorderLayout.EAST , p3p3);
          p3f3.getContentPane().add(BorderLayout.SOUTH , p3p4);
         p3f3.setSize(700,600);
         p3f3.setVisible(true);
}// StartF3()
     //previous button handler
     class P3_Previous implements ActionListener{
          public void actionPerformed(ActionEvent e){
               p3f3.setVisible(false);
               Page1 p1 = new Page1();
               p1.StartF1();
               p1.p1f1.setVisible(true);
// continue button handler
     class p3_Continue implements ActionListener{
          public void actionPerformed(ActionEvent e){
               Name = p3t1.getText();
              UserID = p3t2.getText();
              Pass1 = p3pp1.getText();
              Pass2 = p3pp2.getText();
              Pin = p3t3.getText();
               Page3_NewUser nu = new Page3_NewUser();
//               setting
               Saving s = new Saving();
               s.Save(nu);
               p3f3.setVisible(false);
               Page1 p1 = new Page1();
               p1.StartF1();
               p1.p1f1.setVisible(true);
}// close Page2_NewUser classand here is my Saving class
import java.io.*;
public class Saving  {
public void Save(Object obb){
     try{
     FileOutputStream f = new FileOutputStream("foo.ser");
     ObjectOutputStream ob = new ObjectOutputStream(f);
     ob.writeObject(obb);
     ob.close();
     catch(Exception e){
          e.printStackTrace();
}//method
}// classEven if serializable method does not suits here can anyone get me an idea how to write text file saving method for this .I know all the method like BufferedWriter and all but i want to make it work by getting text from JTextField . ---- plz help
Edited by: aakansha on Feb 22, 2008 11:02 AM

One of your problems is that you are creating a new Page3_NewUser object in the p3_Continue ActionListener and expecting it to contain all of the data contained in the current Page3_NewUser object. Well it won't as the two objects will be totally distinct. You need to use the current Page3_NewUser object in the ActionListener. One way to do this is to use Page3_NewUser.this object like so:
            Saving s = new Saving();
            s.Save(Page3_NewUser.this);

Similar Messages

  • Saving JTextfield Input to a file

    hi i wrote a program that saves the data from a JTextArea into a file
    try {
         String data = jt.getText(); //jt is a JTextArea
         f.createNewFile();
         FileOutputStream fo = new FileOutputStream(file_name);
         int c = 0;
         while(c < data.length()) {
              fo.write((int)data.charAt(c));
              c++;
         fo.close();
    }catch(Exception ec) {
    If i open the file that i saved to using notepad none of the new lines are shown, for example if i write
    Line1
    Line2
    Line3
    Line4
    it is saved as
    Line1Line2Line3Line4

    Adding to what DrClap said, if you must use notepad, then, include the BufferedWriter's "newLine() " method. This will move your text to a new line. The "\n" will not do it, instead, it will leave a solid black square in please of the new line
    BufferedWriter out = new BufferedWriter (
                                           new FileWriter ("file.txt"));
           out.write ("hello");
           out.newLine();
       out.close();

  • Saving ' from JTextField in Database

    Hi
    I am trying to save String that includes ' to database but getting errors. For example "Pack Size 2 x 14's". Error is occured from 's.
    Please Help.
    Mortoza

    Hi
    I have check but found nothing like my problem, can you help?
    Mortoza

  • Saving parameters entered in a gui dialog to be used in the main panel

    Hi,
    I'm having a nightmare at the moment.
    I've finished creating a program for my final year project, that is all comand line at the moment.
    i'm required to design a GUI for this. i've started already and have a main panel that has a few buttons one of which is a setParameters button. which opens up a file dialog that allows the user to enter parameters that will be used by the main panel later on.
    I'm having trouble imagining how these parameters will be accessed by the main Panel once they are saved.
    At the moment, without the GUI i have get and set methods in my main program which works fine. Is this the kind of thing i'll be using for this?
    my code for the parameters dialog
    public class Parameters  extends JDialog
         private GridLayout grid1, grid2, grid3;
         JButton ok, cancel;
            public Parameters()
                    setTitle( "Parameters" );
                    setSize( 400,500 );
                    setDefaultCloseOperation( DISPOSE_ON_CLOSE );
              grid1 = new GridLayout(7,2);
              grid2 = new GridLayout(1,2);
                    JPanel topPanel = new JPanel();
                    topPanel.setLayout(grid1);
              JPanel buttonPanel = new JPanel();
                    buttonPanel.setLayout(grid2);
              ok = new JButton("OK");
                  ok.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                  //when pressed i want to save the parameters that the user has entered
              //and be able to access these in the RunPanel class
              cancel = new JButton("Cancel");
                 cancel.addActionListener(new ActionListener() {
                          public void actionPerformed(ActionEvent e) {
                        //when pressed just want the Jdialog  to close
              buttonPanel.add(ok);
              buttonPanel.add(cancel);
              JTextArea affinityThresholdScalar = new JTextArea();
              JTextArea clonalRate = new JTextArea();
              JTextArea stimulationValue = new JTextArea();
              JTextArea totalResources = new JTextArea();
              JLabel aTSLabel = new JLabel("affinityThresholdScalar");
              JLabel cRLabel = new JLabel("clonalRate");
              topPanel.add(aTSLabel);
              topPanel.add(affinityThresholdScalar);
              topPanel.add(cRLabel);
              topPanel.add(clonalRate);
                    Container container = getContentPane();//.add( topPanel );
              container.add( topPanel, BorderLayout.CENTER );
              container.add( buttonPanel, BorderLayout.SOUTH );
         }the main panel class is:
    public class RunPanel extends JPanel implements ActionListener
         JButton openButton, setParametersButton, saveButton;
         static private final String newline = "\n";
         JTextArea log;
             JFileChooser fc;
         Data d = new Data();
         Normalise rf = new Normalise();
         Parameters param = new Parameters();
        public RunPanel()
            super(new BorderLayout());
            log = new JTextArea(5,20);
            log.setMargin(new Insets(5,5,5,5));
            log.setEditable(false);
            JScrollPane logScrollPane = new JScrollPane(log);
            fc = new JFileChooser();
            openButton = new JButton("Open a File...")
            openButton.addActionListener(this);
         setParametersButton = new JButton("Set User Parameters");
            setParametersButton.addActionListener(this);
         saveButton = new JButton("save");
            saveButton.addActionListener(this);
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            buttonPanel.add(openButton);
         buttonPanel.add(setParametersButton);
         JPanel savePanel = new JPanel();
         savePanel.add(saveButton);
            add(buttonPanel, BorderLayout.PAGE_START);
            add(logScrollPane, BorderLayout.CENTER);
         add(savePanel, BorderLayout.SOUTH);
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(RunPanel.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    log.append("Opening: " + file.getName() + "." + newline);
              Vector data = d.readFile(file);
              log.append("Reading file into Vector " +data+ "." + newline);
              Vector dataNormalised = rf.normalise(data);
             else {
                    log.append("Open command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
         else if (e.getSource() == saveButton) {
                int returnVal = fc.showSaveDialog(RunPanel.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    log.append("Saving: " + file.getName() + "." + newline);
                } else {
                    log.append("Save command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
         else
              if (e.getSource() == setParametersButton)
                    log.append("loser." + newline);
                          param.show();
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("AIRS");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new RunPanel();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Can anybody offer any suggestions?
    Cheers

    What you need is my ParamDialog. I think it could be perfect for this sort of thing. There are a few references in it to some of my other classes namely
    StandardDialog. Which you can find by searching for other posts on this forum. But if you'd rather not find that you could just use JDialog instead
    WindowUtils.visualize() this is just a helper method for getting things visualized on the screen. You can just use setBounds and setVisible and you'll be fine.
    You are welcome to use and modify this code but please don't change the package or take credit for it as your own work.
    If you need to bring up a filedialog or a color chooser you will need to make some modifications. If you do this, would you mind posting that when you are done so that myself and others can use it? :)
    StandardDialog.java
    ================
    package tjacobs.ui;
    import java.awt.Dialog;
    import java.awt.Frame;
    import java.awt.GraphicsConfiguration;
    import java.awt.HeadlessException;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    import java.awt.*;
    import java.util.HashMap;
    import java.util.Properties;
    /** Usage:
    * *      ParamDialog pd = new ParamDialog(new String[] {"A", "B", "C"});
    * pd.pack();
    * pd.setVisible(true);
    * Properties p = pd.getProperties();
    public class ParamDialog extends StandardDialog {
         public static final String SECRET = "(SECRET)";
         String[] fields;
         HashMap<String, JTextField> mValues = new HashMap<String, JTextField>();
         public ParamDialog(String[] fields) throws HeadlessException {
              this(null, fields);
         public ParamDialog(JFrame owner, String[] fields) {
              super(owner);
              setModal(true);
              this.fields = fields;
              JPanel main = new JPanel();
              main.setLayout(new GridLayout(fields.length, 1));
              for (int i = 0; i < fields.length; i++) {
                   JPanel con = new JPanel(new FlowLayout());
                   main.add(con);
                   JTextField tf;
                   if (fields.endsWith(SECRET)) {
                        con.add(new JLabel(fields[i].substring(0, fields[i].length() - SECRET.length())));
                        tf = new JPasswordField();
                   else {
                        con.add(new JLabel(fields[i]));
                        tf = new JTextField();
                   tf.setColumns(12);
                   con.add(tf);
                   mValues.put(fields[i], tf);
              this.setMainContent(main);
         public boolean showApplyButton() {
              return false;
         public void apply() {
         private boolean mCancel = false;
         public void cancel() {
              mCancel = true;
              super.cancel();
         public Properties getProperties() {
              if (mCancel) return null;
              Properties p = new Properties();
              for (int i = 0; i < fields.length; i++) {
                   p.put(fields[i], mValues.get(fields[i]).getText());
              return p;
         public static void main (String[] args) {
              ParamDialog pd = new ParamDialog(new String[] {"A", "B", "C"});
              WindowUtilities.visualize(pd);     
         public static Properties getProperties(String[] fields) {
              ParamDialog pd = new ParamDialog(fields);
              WindowUtilities.visualize(pd);
              return pd.getProperties();          

  • Saving a file from a form to be display on a table

    Hi i'm having some problems trying to save the filled out on the form to be displayed on the table i don't know how i am going to go about it can you please help me thanks.
    Here is the code for the form.
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    import java.net.URL;
    import java.text.ParseException;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.swing.JComboBox;
    public class DD extends JPanel
                                 implements ActionListener {
        private String newline = "\n";
        protected static final String textFieldString = "Name"; 
        protected static final String textFieldString1 = "Start Time";
        protected static final String textFieldString2 = "End Time";
        protected static final String textFieldString3 = "Total Time(Minutes)";
        protected static final String ftfString = "Date";
        protected static final String buttonString = "JButton";
        JFormattedTextField startTime;
        JTextField totalTime;
        protected JLabel actionLabel;
        Component[][] rowData;
        private String[] shapeName = { "Meeting", "Lunch", "Holiday", "Sickness",
                 "Preparing report", "Administrative work", "Emails", "Query" };
        public DD() {
            setLayout(new BorderLayout());
            Panel data = new Panel();
              data.setLayout(new GridLayout(7, 4));
            rowData = new Component[7][];
    //      One row
                   for (int row = 0; row < 7; row++)
                        rowData[row] = new Component[5];
                        rowData[row][0] = new TextField(10);
                        rowData[row][1] = new TextField(10);
                        ((TextField) rowData[row][1]).addActionListener(this);
                        rowData[row][2] = new JComboBox(shapeName);
                        ((JComboBox) rowData[row][2]).addActionListener(this);
    //      ((TextField)rowData[ row ][ 2 ]).addActionListener(this);
                        rowData[row][3] = new TextField(10);
                        ((TextField) rowData[row][3]).addActionListener(this);
    //      JComboBox jcboxShapeCombo;
    //      System.out.println(rowData[row][2]);
    //      jcboxShapeCombo[2] = new JComboBox (shapeName);
    //      rowData[ row ][ 3 ] = new TextField(10);
                        rowData[row][4] = new TextField(10);
                        ((TextField) rowData[row][4]).addActionListener(this);
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
                        ((TextField) rowData[row][0]).setText(sdf.format(new java.util.Date()));
                        data.add(rowData[row][0]);
                        data.add(rowData[row][1]);
                        data.add(rowData[row][2]);
                        data.add(rowData[row][3]);
                        data.add(rowData[row][4]);
            //Create a regular text field.
            JTextField textField = new JTextField(10);
            textField.setActionCommand(textFieldString);
            textField.addActionListener(this);
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
            startTime = new JFormattedTextField(sdf);
            startTime.setValue(new java.util.Date());
            startTime.setActionCommand(textFieldString1);
            startTime.addActionListener(this);
            JTextField textField2 = new JTextField(10);
            textField2.setActionCommand(textFieldString2);
            textField2.addActionListener(this);
            totalTime = new JTextField(10);
            totalTime.setActionCommand(textFieldString3);
            totalTime.addActionListener(this);
            //Create a formatted text field.
            JFormattedTextField ftf = new JFormattedTextField(
                      //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
                    java.util.Calendar.getInstance().getTime());
            ftf.setActionCommand(textFieldString);
            ftf.addActionListener(this);
            //Create some labels for the fields.
            JLabel textFieldLabel = new JLabel(textFieldString + ": ");
            textFieldLabel.setLabelFor(textField);
            JLabel textFieldLabel1 = new JLabel(textFieldString1 + ": ");
            textFieldLabel1.setLabelFor(startTime);
            JLabel textFieldLabel2 = new JLabel(textFieldString2 + ": ");
            textFieldLabel2.setLabelFor(textField2);
            JLabel textFieldLabel3 = new JLabel(textFieldString3 + ": ");
            textFieldLabel3.setLabelFor(totalTime);
            JLabel ftfLabel = new JLabel(ftfString + ": ");
            ftfLabel.setLabelFor(ftf);
            //Create a label to put messages during an action event.
            actionLabel = new JLabel("Type text in a field and press Enter.");
            actionLabel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
            //Lay out the text controls and the labels.
            JPanel textControlsPane = new JPanel();
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            textControlsPane.setLayout(gridbag);
            JLabel[]labels = {textFieldLabel, textFieldLabel1,textFieldLabel2, textFieldLabel3, ftfLabel};
            JTextField[] textFields = {textField, startTime,textField2,totalTime, ftf};
            addLabelTextRows(labels, textFields, gridbag, textControlsPane);
            c.gridwidth = GridBagConstraints.REMAINDER; //last
            c.anchor = GridBagConstraints.WEST;
            c.weightx = 1.0;
            textControlsPane.add(actionLabel, c);
            textControlsPane.setBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Text Fields"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)));
            //Create a text area.
            JTextArea textArea = new JTextArea(
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            areaScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            areaScrollPane.setPreferredSize(new Dimension(250, 250));
            areaScrollPane.setBorder(
                BorderFactory.createCompoundBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Comment"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)),
                    areaScrollPane.getBorder()));
            //Create an editor pane.
            JEditorPane editorPane = createEditorPane();
            JScrollPane editorScrollPane = new JScrollPane(editorPane);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));
            String[] initString =
            { "Meeting", "Lunch", "Holiday", "Sickness",
                     "Preparing report", "Administrative work", "Emails", "Query" };
            JList listCategories = new JList(initString);
            JScrollPane editorScrollPane = new JScrollPane(listCategories);
            editorScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            editorScrollPane.setPreferredSize(new Dimension(250, 145));
            editorScrollPane.setMinimumSize(new Dimension(10, 10));
            //Create a text pane.
            JTextPane textPane = createTextPane();
            JScrollPane paneScrollPane = new JScrollPane(textPane);
            paneScrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            paneScrollPane.setPreferredSize(new Dimension(250, 155));
            paneScrollPane.setMinimumSize(new Dimension(10, 10));
            //Put the editor pane and the text pane in a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  editorScrollPane,
                                                  paneScrollPane);
            splitPane.setOneTouchExpandable(true);
            splitPane.setResizeWeight(0.5);
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(splitPane);
            rightPane.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Category of Task"),
                            BorderFactory.createEmptyBorder(5,5,5,5)));
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(editorScrollPane);
            //Put everything together.
            JPanel leftPane = new JPanel(new BorderLayout());
            leftPane.add(textControlsPane,
                         BorderLayout.PAGE_START);
            leftPane.add(areaScrollPane,
                         BorderLayout.CENTER);
            add(leftPane, BorderLayout.LINE_START);
            add(rightPane, BorderLayout.LINE_END);
            JButton button = new JButton("Submit");
            button.setCursor(Cursor.getDefaultCursor());
            //button.setMargin(new Insets(0,0,0,0));
            button.setActionCommand(buttonString);
            button.addActionListener(this);
            add(button, BorderLayout.SOUTH);
            button.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        String toPrint = collectData();
                        newFile(toPrint);
       private String collectData()
              String toPrint = "";
              for (int i = 0; i < rowData.length; i++)
                   Component[] currentRowComps = rowData;
                   for (int j = 0; j < currentRowComps.length; j++)
                        Component currentComp = currentRowComps[j];
                        if (currentComp instanceof TextField)
                             TextField tf = (TextField) currentComp;
                             toPrint += tf.getText() + " - ";
                        else if (currentComp instanceof JComboBox)
                             JComboBox box = (JComboBox) currentComp;
                             Object selection = box.getSelectedItem();
                             if (selection != null)
                                  toPrint += selection.toString() + " - ";
                   toPrint += "\n";
              return toPrint;
         private File newFile(String data)
              File newfile = null;
              try
                   newfile = new File("I:\\ouput.doc");
                   System.out.println("DATA? - " + data);
                   FileOutputStream fos = new FileOutputStream(newfile);
                   fos.write(data.getBytes());
                   fos.close();
                   // JOptionPane.showMessageDialog(null, "Save File");
                   JOptionPane.showMessageDialog(null, "File saved.", "Success",
                   JOptionPane.INFORMATION_MESSAGE);
              catch (IOException ioexc)
                   JOptionPane.showMessageDialog(null, "Error while saving file: " + ioexc,
                   "Error", JOptionPane.ERROR_MESSAGE);
              return null;
    private void addLabelTextRows(JLabel[] labels,
    JTextField[] textFields,
    GridBagLayout gridbag,
    Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
    for (int i = 0; i < numLabels; i++) {
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0; //reset to default
    container.add(labels[i], c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    public void actionPerformed(ActionEvent e) {
    String prefix = "You typed \"";
    if (textFieldString2.equals(e.getActionCommand()))
    JTextField source = (JTextField)e.getSource();
    actionLabel.setText(prefix + source.getText() + "\"");
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("H:mm");
    try {
                        java.util.Date end = sdf.parse(source.getText());
                        java.util.Date start = sdf.parse(startTime.getText());
                        long difference = (end.getTime() - start.getTime()) / 60000;
                        totalTime.setText(Long.toString(difference));
                   } catch (ParseException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
    if (textFieldString1.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    if (textFieldString2.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    if (textFieldString3.equals(e.getActionCommand()))     {JTextField source = (JTextField)e.getSource();
            actionLabel.setText(prefix + source.getText() + "\"");}
    else if (textFieldString.equals(e.getActionCommand())) {
    //JPasswordField source = (JPasswordField)e.getSource();
    //actionLabel.setText(prefix + new String(source.getPassword())
    //+ "\"");
    } else if (buttonString.equals(e.getActionCommand())) {
    Toolkit.getDefaultToolkit().beep();
    private JEditorPane createEditorPane() {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    java.net.URL helpURL = DD.class.getResource(
    "DailyDairyDemoHelp.html");
    if (helpURL != null) {
    try {
    editorPane.setPage(helpURL);
    } catch (IOException e) {
    System.err.println("Attempted to read a bad URL: " + helpURL);
    } else {
    System.err.println("Couldn't find file: Daily Dairy.html");
    return editorPane;
         private JTextPane createTextPane() {
    String[] initString =
    { "Meeting", "Lunch", "Holiday", "Sickness",
         "Preparing report", "Administrative work", "Emails", "Query" };
    String[] initStyles =
    { "regular", "italic", "bold", "small", "large",
    "regular", "button", "regular", "icon",
    "regular"
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
    for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString[i],
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);}
    /*s = doc.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon pigIcon = createImageIcon("images/Pig.gif",
    "a cute pig");
    if (pigIcon != null) {
    StyleConstants.setIcon(s, pigIcon);
    s = doc.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon soundIcon = createImageIcon("images/sound.gif",
    "sound icon");
    JButton button = new JButton();
    if (soundIcon != null) {
    button.setIcon(soundIcon);
    } else {
    button.setText("BEEP");
    button.setCursor(Cursor.getDefaultCursor());
    button.setMargin(new Insets(0,0,0,0));
    button.setActionCommand(buttonString);
    button.addActionListener(this);
    StyleConstants.setComponent(s, button);
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path,
    String description) {
    java.net.URL imgURL = DD.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL, description);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("DailyDairyDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Add content to the window.
    frame.add(new DD());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event dispatching thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    //Turn off metal's use of bold fonts
              UIManager.put("swing.boldMetal", Boolean.FALSE);
              createAndShowGUI();
    And here is the code for the table.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.util.Date;
    import java.sql.*;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class DDTable extends JFrame{
         protected JTable m_table;
         protected DDTableData m_data;
         protected JLabel m_title;
         public DDTable(){
              super("DDTABLE");
              setSize(600, 300);
              UIManager.put("Table.focusCellHighlightBorder",new LineBorder(Color.black, 0));
              m_data = new DDTableData();
              m_title = new JLabel(m_data.getTitle(), SwingConstants.CENTER);
              m_title.setFont(new Font("Helvetica", Font.PLAIN, 24));
              getContentPane().add(m_title, BorderLayout.NORTH);
              m_table = new JTable();
              m_table.setAutoCreateColumnsFromModel(false);
              m_table.setModel(m_data);
              for (int k = 0; k < m_data.getColumnCount(); k++) {
                   DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
                   renderer.setHorizontalAlignment(DDTableData.m_columns[k].m_alignment);
                   TableColumn column = new TableColumn(k, DDTableData.m_columns[k].m_width, renderer, null);
                   m_table.addColumn(column);
              JTableHeader header = m_table.getTableHeader();
              header.setUpdateTableInRealTime(false);
              setJMenuBar(createMenuBar());
              JScrollPane ps = new JScrollPane();
              ps.getViewport().setBackground(m_table.getBackground());
              ps.getViewport().add(m_table);
              getContentPane().add(ps, BorderLayout.CENTER);
              protected JMenuBar createMenuBar(){
                   JMenuBar menuBar = new JMenuBar();
                   JMenu mFile = new JMenu("File");
                   mFile.setMnemonic('f');
                   Action actionNew = new AbstractAction("New Appointment"){
                        public void actionPerformed(ActionEvent e){
                             if (!promptToSave())
                                  return;
                             newDocument();
                        JMenuItem item = new JMenuItem(actionNew);
                        item.setMnemonic('n');
                        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
                        mFile.add(item);
                        Action actionSave = new AbstractAction("Save Appointment"){
                             public void actionPerformed(ActionEvent e){
                                  boolean m_textChanged = false;
                                  if (!m_textChanged)
                                       return;
                                  saveFile(false);
                              item = new JMenuItem(actionSave);
                             item.setMnemonic('s');
                             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
                             mFile.add(item);
                   JMenuItem mData = new JMenuItem("Retrieve Data");
                   mData.setMnemonic('r');
                   ActionListener lstData = new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        retrieveData();
                   mData.addActionListener(lstData);
                   mFile.add(mData);
                   mFile.addSeparator();
                   JMenuItem mExit = new JMenuItem("Exit");
                   mExit.setMnemonic('x');
                   ActionListener lstExit = new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             System.exit(0);
                   mExit.addActionListener(lstExit);
                   mFile.add(mExit);
                   menuBar.add(mFile);
                   return menuBar;
              protected void saveFile(boolean b) {
                   // TODO Auto-generated method stub
              protected void newDocument() {
                     //Create and set up the window.
                 JDialog frame = new JDialog();//"DailyDairyDemo");
                 frame.setModal(true);
                 //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new DD());
                 //Display the window.
                 frame.pack();
                 frame.setVisible(true);
                 JOptionPane.showMessageDialog(this, "Done!");
                 //loadFile();
              protected boolean promptToSave() {
                   // TODO Auto-generated method stub
                   return true;
              public void retrieveData(){
                   Runnable updater = new Runnable(){
                        public void run(){
                             SimpleDateFormat frm = new SimpleDateFormat("MM/dd/yyyy");
                             String currentDate = frm.format(m_data.m_date);
                             String result =
                             (String)JOptionPane.showInputDialog(DDTable.this,"Please enter date in form mm/dd/yyyy:", "Input", JOptionPane.INFORMATION_MESSAGE, null, null, currentDate);
                             if (result==null)
                                  return;
                             java.util.Date date = null;
                             try{
                                  date = frm.parse(result);
                             catch (java.text.ParseException ex){
                                  date = null;
                             if (date == null){
                                  JOptionPane.showMessageDialog(DDTable.this, result+" is not a valid date", "Warning", JOptionPane.WARNING_MESSAGE);
                                  return;
                             setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                             try{
                                  m_data.retriveData(date);
                             catch (Exception ex){
                                  JOptionPane.showMessageDialog(DDTable.this,"Error retrieving data:\n"+ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
                             setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                             m_title.setText(m_data.getTitle());
                             m_table.tableChanged(new TableModelEvent(m_data));
                   SwingUtilities.invokeLater(updater);
         public static void main(String argv[]){
              DDTable frame = new DDTable();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
       class DDData{
            public String m_name;
            public String m_date;
            public String m_startTime;
            public String m_endTime;
            public String m_totalTime;
            public String m_comment;
            public String m_category;
            public DDData(String name, String date,String startTime, String endTime, String totalTime, String comment, String category){
                 m_name = name;
                 m_date = date;
                 m_startTime = startTime;
                 m_endTime = endTime;
                 m_totalTime = totalTime;
                 m_comment = comment;
                 m_category = category;
       class ColumnData{
            public String m_title;
            public int m_width;
            public int m_alignment;
            public ColumnData(String title, int width, int alignment) {
                 m_title = title;
                 m_width = width;
                 m_alignment = alignment;
       class DDTableData extends AbstractTableModel{
         private static final long serialVersionUID = 1L;
         static final String QUERY = "SELECT symbols.name,"+"data startTime, data.endTime, data.totalTime, data.comment, data.category FROM DATA INNER JOIN SYMBOLS"
         +"ON DATA.symbol = SYMBOLS.symbol WHERE"+
         "month(data.date1)=? AND day(data.date1)=?"+
         "AND year(data.date1)=?";
         @SuppressWarnings("unchecked")
         public void retriveData(Date date)
         throws SQLException, ClassNotFoundException {
              try {
                   File f = new File("appointments.dat");
                   FileInputStream fis = new FileInputStream(f);
                ObjectInputStream ois = new ObjectInputStream(fis);
                m_vector = (Vector<DDData>) ois.readObject();
                ois.close();
                fis.close();
               } catch(ClassCastException ex) {
               } catch(FileNotFoundException ex) {
               } catch(IOException ex) {
              /*GregorianCalendar calendar = new GregorianCalendar();
              calendar.setTime(date);
              int month = calendar.get(Calendar.MONTH)+1;
              int day = calendar.get(Calendar.DAY_OF_MONTH);
              int year = calendar.get(Calendar.YEAR);
              m_date = date;
              m_vector = new Vector();
              Connection conn = null;
              PreparedStatement pst = null;
              try{
                   //Load the JDBC-ODBC bridge driver
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn = DriverManager.getConnection("jdbc:odbc:Market", "admin", "");
                   pst = conn.prepareStatement(QUERY);
                   pst.setInt(1, month);
                   pst.setInt(2, day);
                   pst.setInt(3, year);
                   ResultSet results = pst.executeQuery();
                   while (results.next()){
                        String name = results.getString(1);
                        String startTime = results.getString(2);
                        String endTime = results.getString(3);
                        String totalTime = results.getString(4);
                        String comment = results.getString(5);
                        String category = results.getString(6);
                        m_vector.addElement(new DDData(name, startTime, endTime, totalTime, comment, category, category));
                   sortData();
              finally{
                   if (pst != null )
                        pst.close();
                   if (conn != null)
                        conn.close();
         private void saveData() {
              try {
                   File f = new File("appointments.dat");
                   FileOutputStream fos = new FileOutputStream(f);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(m_vector);
                oos.close();
                fos.close();
               } catch(IOException ex) {
         private void sortData() {
              // TODO Auto-generated method stub
         static final public ColumnData m_columns[] = {
                 new ColumnData("Name", 100, JLabel.LEFT),
                 new ColumnData("Date", 100, JLabel.LEFT),
                 new ColumnData("Start Time", 100, JLabel.RIGHT),
                 new ColumnData("End Time", 100, JLabel.RIGHT),
                 new ColumnData("Total Time", 100, JLabel.RIGHT),
                 new ColumnData("Comment", 200, JLabel.RIGHT),
                 new ColumnData("Category", 100, JLabel.RIGHT),
            protected SimpleDateFormat m_frm;
            protected Vector<DDData> m_vector = new Vector<DDData>();
            protected Date m_date;
            public DDTableData(){
                 m_frm = new SimpleDateFormat("MM/dd/yyyy");
                 setDefaultData();
            public void setDefaultData(){
                 try{
                      m_date = m_frm.parse("07/31/2007");
                 catch (java.text.ParseException ex){
                      m_date = null;
                 m_vector.removeAllElements();
                 m_vector.addElement(new DDData("Jerome", null, "Dan", null, null, null, null));
            public int getRowCount(){
                 return m_vector==null ? 0 : m_vector.size();
            public int getColumnCount(){
                 return m_columns.length;
            public String getColumnName(int column){
                 return m_columns[column].m_title;
            public boolean isCellEditable(int nRow, int nCol){
                 return false;
            public Object getValueAt(int nRow, int nCol){
                 if (nRow < 0 || nRow>=getRowCount())
                      return "";
                 DDData row = m_vector.elementAt(nRow);
                 switch (nCol){
                 case 0: return row.m_name;
                 case 1: return row.m_date;
                 case 2: return row.m_startTime;
                 case 3: return row.m_endTime;
                 case 4: return row.m_totalTime;
                 case 5: return row.m_comment;
                 case 6: return row.m_category;
                 return "";
            public String getTitle(){
                 if (m_date==null)
                      return "Daily Dairy";
                 return "Daily Dairy at "+m_frm.format(m_date);

    here is code to collect the data pls what can i do to get the data on the form display on the JTable in the all categories as on the form pls...
    private String collectData()
              String toPrint = "";
              for (int i = 0; i < rowData.length; i++)
                   Component[] currentRowComps = rowData;
                   for (int j = 0; j < currentRowComps.length; j++)
                        Component currentComp = currentRowComps[j];
                        if (currentComp instanceof TextField)
                             TextField tf = (TextField) currentComp;
                             toPrint += tf.getText() + " - ";
                        else if (currentComp instanceof JComboBox)
                             JComboBox box = (JComboBox) currentComp;
                             Object selection = box.getSelectedItem();
                             if (selection != null)
                                  toPrint += selection.toString() + " - ";
                   toPrint += "\n";
              return toPrint;
         private File newFile(String data)
              File newfile = null;
              try
                   newfile = new File("I:\\ouput.doc");
                   System.out.println("DATA? - " + data);
                   FileOutputStream fos = new FileOutputStream(newfile);
                   fos.write(data.getBytes());
                   fos.close();
                   // JOptionPane.showMessageDialog(null, "Save File");
                   JOptionPane.showMessageDialog(null, "File saved.", "Success",
                   JOptionPane.INFORMATION_MESSAGE);
              catch (IOException ioexc)
                   JOptionPane.showMessageDialog(null, "Error while saving file: " + ioexc,
                   "Error", JOptionPane.ERROR_MESSAGE);
              return null;
    private void addLabelTextRows(JLabel[] labels,
    JTextField[] textFields,
    GridBagLayout gridbag,
    Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
    for (int i = 0; i < numLabels; i++) {
    c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
    c.fill = GridBagConstraints.NONE; //reset to default
    c.weightx = 0.0; //reset to default
    container.add(labels[i], c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    Message was edited by:
    desaint
    Message was edited by:
    desaint

  • Problem with gaining focus for JTextField in JTabPane

    I have 2 tabs. The first one has a "save to file" puush button, the seccond has two textfields. When I push the save button I get a warning that not all fields in the seccond tab are filled. If I choose the first button it shows me the seccond tab and searches for the first empty field. Then it should set the focus to that field but it doesn't. Here's the code:
    void goToEmptyField() {
            tabs.setSelectedIndex(1);
            JTextField field =  (nameField.getText().length() == 0) ? nameField : actionField;
            field.requestFocusInWindow();
        }The code for determining the first empty field works fine. I'm not sure if the seccond tab gets focus or just shows up. It doesn't have the light rectangle at the tab's description. Could anybody help me please?

    seems to work OK in this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      JTabbedPane tabs;
      JTextField nameField = new JTextField(20);
      JTextField actionField = new JTextField(20);
      public Testing()
        setLocation(400,300);
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp1 = new JPanel();
        JButton saveBtn = new JButton("Save");
        saveBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            if(checkFields()) saveData();}});
        jp1.add(saveBtn);
        JPanel jp2 = new JPanel();
        jp2.add(new JLabel("Name: "));
        jp2.add(nameField);
        jp2.add(new JLabel("Action: "));
        jp2.add(actionField);
        tabs = new JTabbedPane();
        tabs.addTab("Tab 1",jp1);
        tabs.addTab("Tab 2",jp2);
        getContentPane().add(tabs);
      public boolean checkFields()
        if(nameField.getText().equals("") || actionField.getText().equals(""))
          JOptionPane.showMessageDialog(this,"field/s empty");
          goToEmptyField();
          return false;
        return true;
      public void goToEmptyField()
        tabs.setSelectedIndex(1);
        JTextField field =  (nameField.getText().length() == 0) ? nameField : actionField;
        field.requestFocusInWindow();
      public void saveData()
        JOptionPane.showMessageDialog(this,"Saving data...");
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Placing a JButton inside a JTextfield aligned to right

    hi,
    i would like to add a JButton inside a JTextField. Actually the textfield shows the current path to which image is saved. So to get a file browser, user will click a small button present inside the textfield and selects the file and simultaneously the text of jtextfield is updated.
    i tried of using jTextField1.add(jButton1); but it has no effect. Neither button was displayed nor any error message was displayed.
    So plzz help me out. thanx

    You shouldn't try to put the JButton in the JTextField. A JTextField isn't meant to hold other components.
    Create a JPanel and add the JTextField and the JButton to it.

  • Real Model View Controller with JTextField

    Hi!
    I am new to Java (so please bear with me). I am building a swing application. I already have added a JTable with a corresponding table model that extends AbstractTableModel. Rather than store the data in the table model, I have modified setValueAt and getValueAt to write and read cell data to another location. So far, everything is fine. When doing setValueAt, I have a fireTableCellUpdated statement that I use to update the edited cell. So far, things are all still fine.
    I would like to do the same thing with a JTextField. I found an example in Core Java Volume 1 for create a class that extends PlainDocument. It uses insertString to update the document in a way that ensures that only numbers are entered. I implemented this. Everything is still fine. I changed insertString to update my remote repository (a field in another class). Everything is still fine. Next, I tried to change (override) both getText methods to read from the repository. This works, but is not reflected on the screen.
    I realize that I need the equivalent of a fireTableCellUpdated statement for the class that extends PlainDocument, but do not know how to do this.
    I have looked a lot over the internet for the model view controller implementation. I know that it can be done using event and event listeners, but this seems to defeat the purpose of the model view controller - it seems like you ought to be able to directly modify the model object to access external data.
    My code is below.
    Thanks/Phil Troy
    * PlainDocument class to make it possible to:
    * - Make sure input in unsigned integer
    * - Automatically save data to appropriate locate
    * This will hopefully eventually work by overriding the insertString and getText methods
    * and creating methods that can be overridden to get and save the numerical value
    class UnsignedIntegerDocument extends PlainDocument
         TutorSchedulerPlusSettings settings;
         JTextField textField;
         public UnsignedIntegerDocument(TutorSchedulerPlusSettings settings)
         {     super();
              this.settings = settings;
         public void setTextField(JTextField textField)
         {     this.textField = textField;
         // Overridden method
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
         {     if (str == null) return;
              String oldString = getText(0, getLength());
              String newString = oldString.substring(0, offs) + str +oldString.substring(offs);
              try
              {     setValue(Integer.parseInt(newString));
                   super.insertString(offs, str, a);
                   fireInsertUpdate(new DefaultDocumentEvent(offs, 10, DocumentEvent.EventType.INSERT));
              catch(NumberFormatException e)
         public String getText()
         {     return String.valueOf(getValue());
         public String getText(int offset, int length) throws BadLocationException
         {     String s = String.valueOf(getValue());
              if (length > 0)
                   s = s.substring(offset, length);
              return s;
         public void getText(int offset, int length, Segment txt) throws BadLocationException
         {     //super.getText(offset, length, txt);
              char[] c = new char[10];
              String s = String.valueOf(getValue());
              s.getChars(offset, length, c, 0);
              txt = new Segment(c, 0, length);
         public String getValue()
         {     int i = settings.maxStudents;
              String s = String.valueOf(i);
              return s;          
         void setValue(int i)
         {     settings.maxStudents = i;
    }

    Hi!
    Thanks for your response. Unfortunately, based on your response, I guess that I must not have clearly communicated what I am trying to do.
    I am using both JTables and JTextFields, and would like to use them both in the same way.
    When using JTable, I extend an AbstractTableModel so that it refers to another data source (in a separate class), rather than one inside of the AbstractTableModel. Thus the getValueAt method, getColumnCount method, setValueAt method, . .. all call methods in another class. The details of that other class are irrelevant, but they could be accessing data from a database (via JDBC) or from other machines via some other communication mechanism.
    I would like to do exactly the same thing with a JTextField. I wish for the data to come from a class other than an object of type PlainDocument, or of any class that implements the Document interface. Instead, I would like to use a class that implements the Document interface to call my external class using methods similar to those found in AbstractTableModel.
    You may ask why I would like to to this. I have specific reasons here, but more generally this would be helpful when saving or retrieving parameters set and displayed in a JTextField to a database, or when sharing JTextField to multiple users located on different machines.
    As to whether this is real MVC or not, I think it is but it really doesn't matter.
    I know that I can accomplish what I want for the JTextField using listeners. However, I would like my code for the JTables to be similarly structured to that of the JTextField.
    Thanks/Phil Troy

  • Add mouselisteners to an array of JTextField objects

    Hi. I am writing a program to emulate a calendar and I though I would do it for each day I would have a JTextField hold the contents of the field. A user could set the event for that time by clicking on the corresponding textfield. I'm still working on saving to file and whatnot, but my question is how can I add motionlisteners to an array of JTextFields?
    Here is what I've written so far:
    for(JTextField c: event)
                   c.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent ev)
                        String in = JOptionPane.showInputDialog("Please Enter event for this time");
                        c.setText(in);
              }I run into I immediate error regarding setting the contents of c within an innerclass. I know it wouldn't be an issue if c was defined as a private variable, but I don't know if that is permitted for the for each loop. Also I get another error I'm not sure of, something about this can only work if the source level is 5.0 which I don't know what that means.
    also outside of this method I've set the object event:
    private JTextField[] event = new JTextField[168];any input would be appreciated.

    When you have an inner class, you can only access variables that are declared final. So, this should work:
    for (int i=0; i <168; i++)
              final JTextField tempEvent = event;
              event[i].addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent ev)
                        String in = JOptionPane.showInputDialog("Please Enter event for this time");
                        tempEvent.setText(in);

  • Editable JTextField in JTable

    Hi,
    My table has 4 columns and n number of rows (coming from Database), one of them is Editable column. I have a JTextField in Editable Column. I want to save changes to database when user is finish editing that column. the way I am saving all data is when user presses "Save" I read all data from Jtable editable column, and save changes. Only problem is that which ever row was user working on last...changes are not registered...for changes to be registerd..user have to select different row..then and only then last working cell/row data gets saved. How do i make sure that all changes are registerd when user presses "save".
    to get value at editable jtextfield column i am using...
    int row = myJTable.getSelectedRow();
    Object jtf_Value = (CustomModel) myJTable.getModel().getValueAt(row, 1);
    by this method, jtf_value returns data before any editing.. (Editiing cell shows new edited value...
    ex. if I edited that column..with 'test data 123'
    and before eidition value was 'testing'
    jtf_Value returns 'testing' Not 'test data 123'
    thank for help in advance.

    The DataModel isn't updated until focus is moved to a different cell. To force updating of the DataModel add the following code at the start of your Save action:
    if ( table.isEditing() )
         int row = table.getEditingRow();
         int col = table.getEditingColumn();
         table.getCellEditor(row, col).stopCellEditing();
    }

  • JTextField does not visualize the text!

    Hello everybody,
    i have a problem with JtextFields.
    I have a Jtable with a ColumnHeader that contains a Button, a combobox and a JTextField.
    Normally i have 3 columns. When i try to move from a textfield to another textfield i can write in this one but the text is not visualized and i do not se the cursor in it.
    If i click a second time in the textfield, then the text gets visible.
    Here after the code of my UIText which extends JTextField.
    package com.wuerth.phoenix.ui;
    import com.wuerth.phoenix.ui.lov.*;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import com.wuerth.phoenix.ui.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.util.Locale;
    import java.text.*;
    import com.wuerth.phoenix.util.PString;
    * This object is a generic ui field. Use them to get alphanumeric
    * text.
    * @author ing. Davide Montesin '99<BR><i>[email protected]</i>
    public class UIText extends JTextField implements TextEditor, PhoenixUIElement, FocusListener, KeyListener, ActionListener
    private DefaultPhoenixUIElement dui;
    // This object (is) was used by updateCorrect to find the correct background color
    // It is used for UIComboBox too.
    // protected final JTextField _jtextfield = new JTextField();
    // Background Color (mtm 010327 - UI Bug)
    private Dimension _preferredSize = null;
    private boolean _onlyUpperCase = false;
    String _oldText;
    * Construct a new UIText with the default length(15).
    public UIText()
    this(15);
    * Construct a new UIText with the specified length.
    public UIText(int length)
    super(length);
    setOnlyUpperCase(UIConfiguration.get().isUITextOnlyUpperCase());
    this._oldText = "";
    this.dui = new DefaultPhoenixUIElement(this);
    this.addFocusListener(this);
    this.addKeyListener(this);
    this.addActionListener(this);
    * Set to true if the object should return only uppercase String. This method
    * have priority over the UIConfiguration.
    * @param c if true the getAsText method will return a uppercase string.
    * @see com.wuerth.phoenix.UIConfiguration#setUITextOnlyUpperCase
    public void setOnlyUpperCase(boolean c)
    _onlyUpperCase = c;
    * Tell the object that this field is required. The field use warning color and error color
    * to tell to the user this requireness.
    public void setRequired(boolean r)
    this.dui.setRequired(r);
    this.updateCorrect();
    * @see setRequired
    public boolean getRequired()
    return this.dui.getRequired();
    * Set the mode for the element. Valid modes are: PhoenixUIElement.INSERT,
    * PhoenixUIElement.LOOKUP AND PhoenixUIElement.FIND. The mode influence the
    * validation process.
    public void setMode(int m)
    this.dui.setMode(m);
    this.updateCorrect();
    * @see setMode
    public int getMode()
    return this.dui.getMode();
    * Use this method to tell this object if it contain semantically correct value. The element
    * itself can't control if semantic is correct. It is responsability of the parent to check
    * semantic of the UIElements value. This method is a way to display that a ArticleNumber is
    * not correct.
    public void setSemanticCorrect(boolean c)
    this.dui.setSemanticCorrect(c);
    this.updateCorrect();
    * @see setSemanticCorrect
    public boolean getSemanticCorrect()
    return this.dui.getSemanticCorrect();
    * This method check if at the moment the uielement is corect at all: syntatically,
    * per range, semantically and requireness.
    * The window can use this method to check if the form can be saved or not.
    public boolean isCorrect()
    return this.dui.isCorrect();
    * This method tell the object to syncronize layout
    * information with the correctness informazion. For example, if
    * the uielement contain a wrong value then after calling this
    * method you are shoure that the background is red(error).
    * <BR>
    * The uiobject itself should call this object at most in this two case:
    * If the lostFocus event fires<BR>
    * If the content of the field is erased.
    // WARNING_COLOR and ERROR_COLOR have priority over
    // EDITABLE_COLOR and NOTEDITABLE_COLOR. (mtm 010327 - UI Bug)
    public void updateCorrect()
    // fire the propertyChange event if necessary before update
    // layout aspect.
    fireUpdate();
    if (isCorrect())
    // (mtm 010327 - UI Bug) Original version.
    // _jtextfield.setEditable(this.isEditable());
    // this.setBackground(_jtextfield.getBackground());
    // this.repaint();
    // Select between EDITABLE and NOTEDITABLE Colors
    setBackground(isEditable() ? EDITABLE_COLOR : NOTEDITABLE_COLOR);
    repaint();
    else
    if (getText().length() == 0)
    // Null object
    setBackground(WARNING_COLOR);
    else
    // Not null object
    setBackground(ERROR_COLOR);
    repaint();
    _setTooltipIfNeeded();
    } // updateCorrect() priority: WARNING_COLOR, ERROR_COLOR */
    * This method tell the object to syncronize layout
    * information with the correctness informazion. For example, if
    * the uielement contain a wrong value then after calling this
    * method you are shoure that the background is red(error).
    * <BR>
    * The uiobject itself should call this object at most in this two case:
    * If the lostFocus event fires<BR>
    * If the content of the field is erased.
    // In this version EDITABLE_COLOR and NOTEDITABLE_COLOR have priority over
    // WARNING_COLOR and ERROR_COLOR.
    public void updateCorrect()
    // fire the propertyChange event if necessary before update
    // layout aspect.
    fireUpdate();
    if (isEditable())
    if (isCorrect())
    setBackground(EDITABLE_COLOR);
    else
    setBackground(getText().length() == 0 ? WARNING_COLOR : ERROR_COLOR);
    else
    setBackground(NOTEDITABLE_COLOR);
    repaint();
    _setTooltipIfNeeded();
    } // updateCorrect() priority: EDITABLE_COLOR, NOTEDITABLE_COLOR/*
    * Overriden setEditable to set editable or not editable Background colors
    * (mtm 010327 - UI Bug)
    public void setEditable(boolean ed)
    super.setEditable(ed);
    // EDITABLE_COLOR and NOTEDITABLE_COLOR have priority over
    // WARNING_COLOR and ERROR_COLOR
    //setBackground(ed ? EDITABLE_COLOR : NOTEDITABLE_COLOR);
    //repaint();
    * Method from FocusListener interface.
    public void focusGained(FocusEvent e)
    System.out.println("show caret");
    setEditable(true);
    Caret caret = getCaret();
    System.out.println(caret);
    caret.setVisible(true);
    //moveCaretPosition(getText().length());
    enableInputMethods(true);
    * Method from FocusListener interface.
    public void focusLost(FocusEvent e)
    // Control if it is all ok
    // Format the field
    if (!e.isTemporary())
    // Make automatic completition when the user leave the field
    enter();
    public void processKeyEvent(KeyEvent e)
    char newKey = e.getKeyChar();
    if (_onlyUpperCase)
    newKey = Character.toUpperCase(e.getKeyChar());
    super.processKeyEvent(new KeyEvent(this, e.getID(), e.getWhen(), e.getModifiers(), e.getKeyCode(), newKey));
    e.consume();
    public void keyTyped(KeyEvent e)
    public void keyPressed(KeyEvent e)
    if (e.getKeyCode() == e.VK_F9)
    if (this.dui.getLOV() != null)
    this.dui.getLOV().addActionListener(this);
    this.dui.getLOV().start(this);
    public void keyReleased(KeyEvent e)
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource() == this)
    enter();
    else
    this.dui.getLOV().removeActionListener(this);
    if (this.dui.getLOV().getValue() != null)
    javax.swing.FocusManager.getCurrentManager().focusNextComponent(this);
    dui.fireEditingCompleted(this);
    //--------------- controlla dimensione del testo... mi sembra pesantuccio!-----------------//
    // FontMetrics fm = this.getGraphics().getFontMetrics(this.getFont());
    FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(this.getFont());
    private void _setTooltipIfNeeded()
    String text = this.getText();
    int tWidth = fm.stringWidth(text);
    int cWidth = this.getSize().width;
    if(tWidth>cWidth && cWidth>0)
    this.setToolTipText(text);
    else
    this.setToolTipText(null);
    * JTextField setText method redefined to perform validation.
    public void setText(String text)
    if (_onlyUpperCase && text !=null)
    text = text.toUpperCase();
    super.setText(text);
    if ((this.getLOV() != null))
    if (this.getLOV().isWorking())
    return;
    updateCorrect();
    setCaretPosition(0);
    dui.fireEditingCompleted(this);
    * Sets the current text.
    public void setValue(String text)
    setAsText(text);
    * Returns the current text.
    public String getValue()
    return getAsText();
    public void setAsText(String text)
    this.setText(text);
    public String getAsText()
    String ret = this.getText();
    if (_onlyUpperCase)
    ret = ret.toUpperCase();
    return PString.trim(ret);
    public void setLOV(LOVWindow lw)
    this.dui.setLOV(lw);
    this.updateCorrect();
    public LOVWindow getLOV()
    return this.dui.getLOV();
    public Dimension getMinimumSize()
    if (_preferredSize == null)
    _preferredSize = super.getPreferredSize();
    return _preferredSize;
    public Dimension getPreferredSize()
    if (_preferredSize == null)
    _preferredSize = super.getPreferredSize();
    return _preferredSize;
    public void setColumns(int colno)
    // invalidate cached data
    super.setColumns(colno);
    _preferredSize = null;
    private void fireUpdate()
    boolean oldSemanticCorrect = this.dui.getSemanticCorrect();
    this.dui.setSemanticCorrect(true);
    boolean correct = this.isCorrect();
    this.dui.setSemanticCorrect(oldSemanticCorrect);
    if ((correct == false) && (this.getAsText().trim().length() != 0))
    return;
    String localOldText = this._oldText;
    this._oldText = this.getAsText();
    firePropertyChange(PhoenixUIElement.ASTEXT_PROPERTY_NAME,localOldText,this._oldText);
    * Inform the component that the editing is completed.
    public void enter()
    if ((this.getMode() == PhoenixUIElement.LOOKUP) && (this.getLOV() != null) && (this.getAsText().length() != 0))
    this.getLOV().isCorrectAuto(this);
    updateCorrect();
    dui.fireEditingCompleted(this);
    * This event is common to all uielement. The event editingCompleted is
    * fired each time the editing reach a complete form. Each swing ui element
    * has a different event to inform that the editing is completed: actionPerformed
    * on the JText, ItemSelected on the JList, focusLost to all elements.
    * <P>
    * <PRE><CODE>
    * actionPerformed focusLost itemsSelected ... enter()
    * \ | / /
    * \ | / _________/
    * \ | / ______/
    * editingCompleted <---------------- setAsText()
    * |
    * |
    * setRequired() ---> updateCorrect
    * setMode() ------/ |
    * |
    * |
    * propertyChange (ASTEXT)
    * </CODE></PRE>
    * Each specific event is mapped on the editingCompleted event. The editing
    * complete event fires an updateCorrect method's call. The updateCorrect
    * fires a propertyChange event if, and only if, the content of
    * the ui element is changed.
    public void addEditingListener(EditingListener ee)
    dui.addEditingListener(ee);
    * Removes the editingListener.
    public void removeEditingListener(EditingListener ee)
    dui.removeEditingListener(ee);
    * This method can be used as common way to set the value for
    * the ui element throught an object. If the object is of the
    * wrong type (like Date for a numeric) no set is made.
    public Object getAsObject()
    return this.getAsText();
    * Return the value in the field as object. For example UIDate return
    * a date object, UINumeric a Double object, UICheckBox a Boolean object, ecc.
    public void setAsObject(Object o)
    if (o instanceof String)
    this.setAsText((String)o);
    * Returns true if the editor is empty. False otherwise.
    public boolean isNull()
    return (this.getAsText().length() == 0);
    * Return the component associated with this editor. In the most cases
    * this is returned.
    public Component getComponent()
    return this;
    public String format(Object o, String pattern)
    return o.toString();
    public String format(Object o, String pattern, Locale l)
    return o.toString();
    public Object parse(String text) throws ParseException
    return text;
    public Object parse(String text, Locale l) throws ParseException
    return text;
    public String getPattern()
    return "";
    public int getAlignment()
    return JLabel.LEFT;
    public Object clone()
    UIText clone = new UIText();
    clone.setText(getText());
    return clone;
    try
    catch (CloneNotSupportedException cnse)
    throw new RuntimeException("Clone not supported?");
    private boolean _noFirePropertyChange = false;
    public void addNotify()
    _noFirePropertyChange = true;
    super.addNotify();
    _noFirePropertyChange = false;
    protected void firePropertyChange(String propertyName,Object oldValue,Object newValue)
    if (!_noFirePropertyChange)
    //System.out.println("NO!");
    if (propertyName.equals("ancestor"))
    return;
    super.firePropertyChange(propertyName, oldValue, newValue);
    public String getMultilangCode()
    return dui.getMultilangCode();
    public String getTooltipMultilangCode()
    return dui.getTooltipMultilangCode();

    Can you explain what are you trying to copy and where?
    Can't you copy text from website to the clipboard or do you have a problem with pasting that text?
    * http://kb.mozillazine.org/Clipboard_not_working

  • PROBLEM Saving Textfield contents

    Hi,
    I am new to Java to start with... I am trying to save the contents of various JTextFields in a text file each one at a different line.
    So far I have come up with the following:
    ====================================
    try {
    FileOutputStream fos = new FileOutputStream("mcsim.rtf");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    System.out.println("saving....");
    String temp = Frame1.inputName.getText();
    System.out.println("saving...." + temp);
    oos.writeChars(temp);
    String LINE_SEP = System.getProperty("line.separator");
    oos.writeObject(LINE_SEP);
    oos.writeChars(jTextField3.getText());
    fos.flush();
    oos.close();
    fos.close();
    System.out.println("Saved");
    catch (IOException f) {
    f.printStackTrace();
    ===============================
    BUT
    1. I get spaces between the characters in my output file
    2. I cannot change line
    3. I get some symbols at the start of the line that I do not know how to get rid of them.
    Any ideas...
    Thanking in advance
    Sotirios

    I mean: :-)
    Don't use an ObjectOutputStream - its for
    serialization. Use PrintStream for plain text:
    try {
    FileOutputStream fos = new
    w FileOutputStream("mcsim.rtf");
    PrintStream ps = new PrintStream (fos);
    System.out.println("saving....");
    String temp = Frame1.inputName.getText();
    System.out.println("saving...." + temp);
    ps.println(temp);
    //String LINE_SEP =
    = System.getProperty("line.separator");
    //oos.writeObject(LINE_SEP);
    //oos.writeChars(jTextField3.getText());
    ps.flush();
    System.out.println("Saved");
    catch (IOException f) {
    f.printStackTrace();

  • Error While saving a iBot

    Hi All ,
    I am getting the below error while saving a iBot.
    Oracle BI Scheduler Error: [nQSError: 16001] ODBC error state: S1C00 code: 106 message: [Microsoft][ODBC Excel Driver]Optional feature not implemented . at stage of execute transaction command with data source: Procurement_Demo
    I am using xls as a datasource to create Repository. I have created scheduler tables for iBot in the same datasource.
    Can i not use XLS as a datasource for iBot?
    If i can use , what is the solution of this problem.
    Thanks in advance.
    -- Ashish

    Hi Vivek,
    Please close your SharePoint Designer application, clear/delete the cached files and folders under the following directories from your server installed SharePoint Designer, then check results again.
    <user profile>\appdata\roaming\microsoft\SharePoint Designer\ProxyAssemblyCache
    <user profile>\appdata\local\microsoft\websitecache\<sitename>
    http://www.andreasthumfart.com/2013/08/sharepoint-designer-2013-server-side-activities-have-been-updated/
    Thanks
    We are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Can not refresh page after save properly(When not saving master record)

    I am using jdeveloper 11g R2 (11.1.2.3) JSF Facelet
    In some use case I have Address as master table and Person as detail table
    For some business reason I need to don't save same addresses
    eg:
    If +1 Test St+ is in database already and new user coming and adding this address with new person
    I need to use the row in database not creating a new address
    I do saving in doDML method of Address with some hashing algorithm and it is fine
    My problem is that I can not refresh page after save properly
    User coming to page think Adding a new address and a new person but in fact no new
    address added because of business I describe above
    Any ideas how I can implement this?
    Appreciate that
    Regards
    Mohsen

    Hi,
    from your description it is not clear why the page doesn't refresh. It could be a problem in your implementation code - who knows. What if you perform the address check on a command button that actually submits the new address? If the check returns true (address exists) you would call row.refresh(forget new row); and re-query the view object so the address coming from the database is displayed. If you wanted to use the doDML then yuou need to be aware that doDML doesn't help removing the row the user created. It just ignores the database update but the entity is still around, which in my suggested solution wont be the case.
    Frank

  • IPhone 4 Voice Memos not working/saving

    Hi there,
    I'm having trouble with my voice memos too. Up until yesterday they were working fine and now, even though the record button works, the stop button does not and I can only pause them. Worse again is that the button to go into the menu to view all voice memos is not working so I can't play them from my iPhone and nothing new is saving to my iTunes. Please help!

    I've always had the "Include Voice Memos" option selected. I think that only pertains to syncing voice memos from iTunes to the iPhone after it has been copied to iTunes. It has to be the new OS/iTunes not communicating that new memos have been recorded. For some reason they won't sync when I want them to, and then a few syncs later they magically appear.
    By the way, I'm VERY comfortable with the iTunes and iPhone systems. I've been using iTunes for 5 years, and I've been recording class lectures with the iPhone voice memo app (and another app) for a couple years. It's not an error of not seeing that the memos were added; they don't exist in my library or music folders.
    JUST OUT OF CURIOSITY, POST WHICH FIRMWARE YOU ARE RUNNING EXACTLY!!!
    I'm on an iPhone 4, running firmware 4.0.1

Maybe you are looking for

  • Need to Disable file sharing via blue tooth?

    Hi Team, Please let me know the steps for disable the file transfer via blue tooth. Thanks and Regards Sahab

  • IMessage is disabled automatically

    Hey all, My iMessage service will disable itself after I turn on. The scenario is like this: 1. I registerd my iMessage with my Apple ID and toggled iMessage on in Setting 2. I am able to send the iMessage. 3. After few week, I found out the iMessage

  • Error: 1056550: Unable to resolve hostname

    Hello Experts, When trying to open the already existing partition definitions, the following error occurs Error: 1056550: Unable to resolve hostname Any suggestions would be of great help. Regards, Sudhir

  • Mail 5.0 appearance

    My new MacBook Air Mail program was displaying mail as boxes, or envelopes, now just lines.  How can I regain the cool appearance?

  • How to see when and who made changes in some table???

    How to see when and who made changes in some table? Some makes me problems and I want to see who are the usernames. Thanks