Results 1 to 5 of 5
  1. #1
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default [SOLVED] Inserting at the cursor/Pointer location in a JTextField.

    Okay I need some help. This is my first time doing this and am at a point where I can not continue on my own. I have been trying to solve the problem for a few days now.

    In a JTextField I can get the Pointer location with
    Java Code:
    	        	PointerInfo a = MouseInfo.getPointerInfo();
    	        	Point b  = a.getLocation();
    	        	int x = (int)b.getX();
    	        	int y = (int)b.getY();
    Now this is the problem. How do I insert a character at that point and move it one to the right?
    I'm using multiply JTextFields and would like to insert the character at any point in any JTextField.
    Can some one please help me.

    Thanks
    Cary
    Last edited by caryr; 06-21-2009 at 11:20 PM. Reason: change any point and any JTextFiled to any point in any JTextField

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    The superclass JTextComponent has some useful methods.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class TextInsertion extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            //System.out.printf("p = [%d, %d]%n", p.x, p.y);
            JTextField tf = (JTextField)e.getComponent();
            int pos = tf.viewToModel(p);
            tf.setCaretPosition(pos);
            try {
                String text = "X";
                tf.getDocument().insertString(pos, text, null);
            } catch(BadLocationException ble) {
                System.out.println("insert error: " + ble.getMessage());
            }
        }
    
        private JPanel getFirst() {
            JTextField textField = new JTextField("Hello World", 12);
            textField.addMouseListener(this);
            JPanel panel = new JPanel();
            panel.add(textField);
            return panel;
        }
    
        private JPanel getLast() {
            JTextField textField = new JTextField(12);
            JPanel panel = new JPanel();
            panel.add(textField);
            return panel;
        }
    
        public static void main(String[] args) {
            TextInsertion test = new TextInsertion();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getFirst(), "First");
            f.add(test.getLast(), "Last");
            f.setSize(200,140);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }

  3. #3
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    Hi Hardwired,
    I can see where your going but I want the user to be able to click on a button and at that point the infinity symbol should be entered in the JTextFiled.
    I cut this down to less then a 1/4 and I still think its to long but I wanted you to see where I was going and help steer me in the right directions. I'm new to all this.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.IOException;
    import java.util.*;
    import javax.swing.*;
    public class RollerDerbyDriver extends JFrame implements ActionListener
    {
    	static JFrame setup;
    	static String inifinity = "\u221E";
    		// Sets up the GUI and does the work.
        private static void createAndShowGUI() 
        {
            setup = new JFrame("Roller Derby Penalty Setup");
            setup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel Home = new JPanel();
            JPanel Vistors = new JPanel();
            Home.setLayout(new GridLayout(4,5));
            Vistors.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            	// The Labels an text fields setup for the home team.
            JLabel HTeamName = new JLabel("Home Team Name");
            final JTextField HTeamNameText= new JTextField(30);
            JLabel HPlayer1Name = new JLabel("Home Player 1 Name");
            final JTextField HPlayer1NameText = new JTextField(30);
            JLabel HPlayer1Number = new JLabel("Home Player 1 Number");
            final JTextField HPlayer1NumberText = new JTextField(30);                
            	// Places the labels and test field in the JPanel named home in a ordered location.
            Home.add(HTeamName); 
            Home.add(HTeamNameText);
            Home.add(HPlayer1Name); 
            Home.add(HPlayer1NameText);
            Home.add(HPlayer1Number);
            Home.add(HPlayer1NumberText);
                   	// Create the JButton Inifinity.
            setup.setLayout(new GridLayout(3,4));
            JButton Inifinity = new JButton(inifinity);
            setup.add(Home);        
            setup.add(Inifinity);
            setup.setLocation(300,200);
            setup.pack();
            setup.setVisible(true);       	
            	// This is the actionListener for the JButton. I can get the location on the Pointer
            	// now at that location I wish to add the infinity symbol to that location.
            	// The JTextField should not matter. I want to add it to all of them at any location
             	// in them. Be it the start, middle or end.    
            Inifinity.addActionListener(
    	      new ActionListener()
    	      {
    	        public void actionPerformed(ActionEvent e)
    	        {
    	        	PointerInfo a = MouseInfo.getPointerInfo();
    	        	Point b  = a.getLocation();
    	        	int x = (int)b.getX();
    	        	int y = (int)b.getY();
    	        	System.out.println("x: " + x + " y: " + y);
    	        	String text = HPlayer1NameText.getText();
    	        		// This is wrong I need to be able to select the right textfield to insert the 
    	        		// infinity Symbol into.
    	        	HPlayer1NameText.setText(text + inifinity);	
    	        }  // end actionPreformed
    	      }  // end ActionListener
    	     ); // end addActionListener Inifinity
        } // end createAndShowGUI
        public static void main(String[] args)
        {
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() 
              {
                  public void run() 
                  {
                      createAndShowGUI();
                  } // end run
              } // end java.swing
            );// end java.swing
        } // end main
        public void actionPerformed(ActionEvent arg0)
        {
          // TODO Auto-generated method stub
          
        }	// end void actionPerformed
      }

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    PointerInfo a = MouseInfo.getPointerInfo();
    Point b  = a.getLocation();
    int x = (int)b.getX();
    int y = (int)b.getY();
    System.out.println("x: " + x + " y: " + y);
    This will give the location of the mouse pointer which, if you use the mouse to select the button will be over the JButton; probably not what you want for this.

    You need a way to select the textField for the insertion. If you use the mouse to click the button the button has the focus and no textField can be focused.
    Other options:
    1 provide the user with a way to select the textField target for the insertion, eg, radio buttons.
    2 Use a key binding for the insert action and insert the symbol at the cursor location in the selected textField. The textfield that has focus and has the cursor in it will be the target.
    Here's one way you could implement option 2.
    With the cursor in any textField hold down the "Control" key and press the "I" (as in India) key.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class RDD
    {
        String inifinity = "\u221E";
    
        private JPanel getUI()
        {
            JPanel Home = new JPanel(new GridLayout(3,0));
            // The Labels an text fields setup for the home team.
            JLabel HTeamName = new JLabel("Home Team Name");
            JTextField HTeamNameText = new JTextField(30);
            JLabel HPlayer1Name = new JLabel("Home Player 1 Name");
            JTextField HPlayer1NameText = new JTextField(30);
            JLabel HPlayer1Number = new JLabel("Home Player 1 Number");
            JTextField HPlayer1NumberText = new JTextField(30);
            // Places the labels and test field in the JPanel named
            // home in a ordered location.
            Home.add(HTeamName);
            Home.add(HTeamNameText);
            Home.add(HPlayer1Name);
            Home.add(HPlayer1NameText);
            Home.add(HPlayer1Number);
            Home.add(HPlayer1NumberText);
            return Home;
        }
    
        private void registerKeys(JFrame f)
        {
            JRootPane rootPane = f.getRootPane();
            int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
            KeyStroke keyStroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_I,
                                       InputEvent.CTRL_DOWN_MASK, true);
            rootPane.getInputMap(c).put(keyStroke, "INSERT");
            rootPane.getActionMap().put("INSERT", insertAction);
        }
    
        private Action insertAction = new TextAction("")
        {
            public void actionPerformed(ActionEvent e)
            {
                JTextComponent target = getFocusedComponent();
                int pos = target.getCaretPosition();
                try {
                    target.getDocument().insertString(pos, inifinity, null);
                } catch(BadLocationException ble) {
                    System.out.println("insert error: " + ble.getMessage());
                }
            }
        };
    
        public static void main(String[] args)
        {
            RDD app = new RDD();
            JFrame setup = new JFrame("Roller Derby Penalty Setup");
            setup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setup.add(app.getUI());
            setup.setLocation(300,200);
            setup.pack();
            setup.setVisible(true);
            app.registerKeys(setup);
        }
    }
    For more on key binding see How to Use Key Bindings.

  5. #5
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    thank you so much Hardwired. This helps me out a lot. I'm still getting to know the java language and I find it quit interesting and I love working with it.
    Thanks for all your help.

Similar Threads

  1. How to Hide cursor
    By priya in forum Java Software
    Replies: 1
    Last Post: 12-09-2010, 10:39 PM
  2. Replies: 1
    Last Post: 01-30-2009, 07:44 PM
  3. Cursor Size
    By ScottVal in forum AWT / Swing
    Replies: 1
    Last Post: 01-03-2009, 07:11 AM
  4. Cursor
    By serfster in forum New To Java
    Replies: 2
    Last Post: 06-15-2008, 06:49 AM
  5. Using a cursor
    By notnumber6 in forum New To Java
    Replies: 3
    Last Post: 11-26-2007, 11:56 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •