Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: Auto Select

  1. #1
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Auto Select

    How do you utilize the AutoSelect class after you make it?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    public class AutoSelect extends FocusAdapter {
    		public void focusGained(FocusEvent e)
    		{
    			if (e.getComponent() instanceof JTextField)
    			{
    				JTextField t = (JTextField) e.getComponent();
    				t.selectAll();
    			}
    		}
    	}


    I need to have the text field called scoreTextField be able to be auto highlighting the data in the field automatically but can't figure out how to implement it.


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Auto Select

    If it's an instance of JTextField, why cast it at all? (Maybe I'm wrong here.)

    You're selecting all the text, but it appears you're doing nothing with it.

    Anyway, you can set the background color by t.setBackground(Color.Whatever);

    I found a class to Highlight.

    As for automatically doing it, maybe one of these classes will help.
    Java 2 Platform SE v1.3.1: Class DefaultHighlighter
    If not, you could always have like an invisible component, a JButton or something like that and give it a Listener and tell it to like button.doClick() or item.setSelected(), or something like that.

    Edit: Ok. I guess the if loop is to keep it from casting something that's not a JTextField. Keep the cast.
    Anyway, I've always wondered how to get a Highlighter to work myself.
    Last edited by javapenguin; January 14th, 2011 at 05:15 PM. Reason: Keep the cast

  3. #3
    Member DavidFongs's Avatar
    Join Date
    Oct 2010
    Location
    Minneapolis, MN
    Posts
    107
    Thanks
    1
    Thanked 45 Times in 41 Posts

    Default Re: Auto Select

    Quote Originally Posted by javapenguin View Post
    If it's an instance of JTextField, why cast it at all? (Maybe I'm wrong here.)
    You are. e.getComponent() returns an object of type Component. Without the cast, there is a compiler error

  4. The Following 2 Users Say Thank You to DavidFongs For This Useful Post:

    copeg (January 14th, 2011), javapenguin (January 14th, 2011)

  5. #4
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    Yeah, the goal of this is to just to give focus to the textfield so the user can automatically start typing into the field instead of having to click it and manually delete the text already there. I just don't know how to implement it to always give focus to the textfield with the text in it already highlighted (thus you can start typing and it deletes the previous text)

  6. #5
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Auto Select

    Quote Originally Posted by _lithium_ View Post
    Yeah, the goal of this is to just to give focus to the textfield so the user can automatically start typing into the field instead of having to click it and manually delete the text already there. I just don't know how to implement it to always give focus to the textfield with the text in it already highlighted (thus you can start typing and it deletes the previous text)
    If the goal is to just give the JTextField focus, call requestFocus() on the component.

  7. #6
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    "Create an AutoSelect class at the end of this StudentsScoresApp class that highlights all of the data in the scoreTextField when the mouse is clicked on that TextField. That way, the user doesn’t have to manually highlight the preceding score just to enter a new score."

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.lang.Math;
     
    public class StudentScoresApp	{
        public static void main(String[] args)	    {
     
    		System.out.println("  List of Student Scores Entered");
            JFrame frame = new StudentScoresFrame();
            frame.setVisible(true);
        }
    }
     
    class StudentScoresFrame extends JFrame		{
        public StudentScoresFrame()		{
            setTitle("Test Scores");
            setSize(250, 250);
            centerWindow(this);
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new StudentScoresPanel();
            this.add(panel);
        }
    private void centerWindow(Window w) {
    	Toolkit tk = Toolkit.getDefaultToolkit();
    	Dimension d = tk.getScreenSize();
    	setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    	}
    }
     
    class StudentScoresPanel extends JPanel implements ActionListener	{
        private JTextField  scoreTextField,
                            countTextField,
                            averageTextField,
                            bestTextField,
                            lowestTextField;
        private JLabel      scoreLabel,
                            countLabel,
                            averageLabel,
                            bestLabel,
                            lowestLabel;
        private JButton     enterScoreButton,
        					clearButton,
                            exitButton;
     
    	private int count = 0;
     
    	private double total = 0;
     
    	// total is a double to prevent truncation when
    	// calculating the average
    	private double average = 0;
    	private int best = 0;
    	private int lowest = 100;
     
        public StudentScoresPanel()	   {
            // display panel
            JPanel displayPanel = new JPanel();
            displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
     
     
            // score label
            scoreLabel = new JLabel("Test score:");
            displayPanel.add(scoreLabel);
     
            // score text field
            scoreTextField = new JTextField(10);
            displayPanel.add(scoreTextField);
            scoreTextField.requestFocus();
            scoreTextField.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				scoreTextField.selectAll();
    			}
    		});
     
            // count label
            countLabel = new JLabel("Number of scores:");
            displayPanel.add(countLabel);
     
            // count text field
            countTextField = new JTextField(10);
            countTextField.setEditable(false);
            countTextField.setFocusable(false);
            displayPanel.add(countTextField);
     
            // average label
            averageLabel = new JLabel("Average score:");
            displayPanel.add(averageLabel);
     
            // average text field
            averageTextField = new JTextField(10);
            averageTextField.setEditable(false);
            averageTextField.setFocusable(false);
            displayPanel.add(averageTextField);
     
            // best label
            bestLabel = new JLabel("Highest score:");
            displayPanel.add(bestLabel);
     
            // best text field
            bestTextField = new JTextField(10);
            bestTextField.setEditable(false);
            bestTextField.setFocusable(false);
            displayPanel.add(bestTextField);
     
            // lowest label
            lowestLabel = new JLabel("Lowest score:");
            displayPanel.add(lowestLabel);
     
            // lowest text field
            lowestTextField = new JTextField(10);
            lowestTextField.setEditable(false);
            lowestTextField.setFocusable(false);
            displayPanel.add(lowestTextField);
     
            // button panel
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
     
            // enter score button
            enterScoreButton = new JButton("Enter Score");
            enterScoreButton.addActionListener(this);
            buttonPanel.add(enterScoreButton);
     
            // clear button
            clearButton = new JButton("Clear");
            clearButton.addActionListener(this);
            buttonPanel.add(clearButton);
     
            // exit button
            exitButton = new JButton("Exit");
            exitButton.addActionListener(this);
            buttonPanel.add(exitButton);
     
            // add panels to main panel
            this.setLayout(new BorderLayout());
            this.add(displayPanel, BorderLayout.CENTER);
            this.add(buttonPanel, BorderLayout.SOUTH);
        }
     
     
        public void actionPerformed(ActionEvent e)	{
            Object source = e.getSource();
            if (source == exitButton){
            	if (count == 0){
    				lowest = 0;}
     
    			NumberFormat ef = NumberFormat.getNumberInstance();
                ef = new DecimalFormat("###.00");
    			System.out.println("\n  Highest: " + best + "  Lowest: " + lowest + "  Average: " + ef.format(average) + "\n");
     
    				System.out.printf("  Program terminated by the User.");
     
                System.exit(0);
    		}
          else if (source == enterScoreButton)	{
                // parse the score
                int score = Integer.parseInt(scoreTextField.getText());
    			// calculate the results
                total += score;
                count++;
                average = total / count;
                if (score > best)
                	best = score;
     
                if (score < lowest)
                	lowest = score;
     
    			NumberFormat df = NumberFormat.getNumberInstance();
                NumberFormat nf = NumberFormat.getNumberInstance();
                df = new DecimalFormat("###.00");
                countTextField.setText(nf.format(count));
                averageTextField.setText(df.format(average));
                bestTextField.setText(nf.format(best));
                lowestTextField.setText(nf.format(lowest));
                System.out.println("  " + nf.format(count) + ". " + score);
    			scoreTextField.selectAll();
            }
            else if (source == clearButton)		{
    			if (count == 0)
    				lowest = 0;
    			NumberFormat df = NumberFormat.getNumberInstance();
                df = new DecimalFormat("###.00");
    			System.out.println("\n  Highest: " + best + "  Lowest: " + lowest + "  Average: " + df.format(average) + "\n");
    			System.out.println("  Scores were cleared...\n  Next Set:");
    			count = 0;
    			total = 0;
    			average = 0;
    			best = 0;
    			lowest = 0;
     
                scoreTextField.setText("");
    			countTextField.setText("");
                averageTextField.setText("");
                bestTextField.setText("");
                lowestTextField.setText("");
    		}
        }
    }
    Last edited by _lithium_; January 14th, 2011 at 10:57 PM.

  8. #7
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Lightbulb Re: Auto Select



    Now I get what you wanted.

    Here's what you should do.

    Create a class called AutoSelect that has a static method that takes a textField(or TextArea), whichever you're using , and selects it. I don't know why so I'm taking a JTextComponent, which is the superclass of JTextArea and JTextField anyway, as a parameter.

    public class AutoSelect()
    {
     
    public static void selectAll(JTextComponent jtc)
    {
    jtc.selectAll();
    }

    And later, in your class with the JTextComponent,
    JTextComponent whatever = new JTextComponent();
     
    whatever.addMouseListener(new MouseListener() {
     
    // implement Mouse Listener methods.
    // for moused clicked 
    // AutoSelect.selectAll(whatever);
    });

    Try that.

  9. #8
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Auto Select

    Change it to JTextField if you want, though it'll still work as JTextComponent as parameter for the static method. In fact, the way I have it, it'll work with JTextAreas too.

  10. #9
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Auto Select

    I don't know why you can't just tell it to selectAll() in the MouseListener without even bothering with another class. But if you must, what I posted should work.

  11. #10
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    Yeah I tried the above coding and it didn't seem to work, It keeps saying "StudentScoresApp.java:149: '{' expected
    public class AutoSelect()"
    ^

    I implemented this:
    		  	scoreTextField.addFocusListener(new java.awt.event.FocusAdapter() {
    		      public void focusGained(java.awt.event.FocusEvent evt) {
    		          scoreTextField.selectAll();
    		      }
    			});
    within the "Enter Score" button and it seems to perform the same function but doesn't generate the "AutoSelect.class" that is wanted. (it says StudentScoresApp.java should generate that .class file.

  12. #11
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    I'm completely confused on this portion still, I got it to the point where it generates an autoselect.class when the app is ran but can't figure out where/how to use it... in the main app:
     class AutoSelect extends FocusAdapter {
    	public void focusGained(FocusEvent e)
    			{
    				if (e.getComponent() instanceof JTextField)
    				{
    					JTextField t = (JTextField) e.getComponent();
    					t.selectAll();
    				}
    			}
    	}

    I've tried doing something like this within the panel:
            // score text field
            scoreTextField = new JTextField(13);
            displayPanel.add(scoreTextField);
            AutoSelect.focusGained(scoreTextField);

    I just need to have the scoreTextField have all the text selected once it is clicked just once.

  13. #12
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    How do I call to an inner class like the above example code?

  14. #13
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Auto Select

    Check the API for JTextField, in particular the addFocusListener method, and suggested reading: How to write a FocusListener

  15. #14
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    I've tried that. I think the focus listener doesn't have what i'm looking for.

    ::Edit::

    I think all I need to do is know how to pass to this now:
     class AutoSelect extends  MouseAdapter {
    	public void mouseClicked(MouseEvent e)
    			{
    				if (e.getComponent() instanceof JTextField)
    				{
    					JTextField t = (JTextField) e.getComponent();
    					t.selectAll();
    				}
    			}
    	}

    i can't seem to figure out how to because I don't knwo how to pass to it and also where in my code to do so.

    I just need it to auto select all the text in the JTextfield once the box is clicked once, instead of the user having to highlight it all them selves and delete it.
    Last edited by _lithium_; January 17th, 2011 at 03:33 PM.

  16. #15
    Junior Member
    Join Date
    May 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Auto Select

    maybe u already found your answer.
    just like the u added the actionlistener to the buttons u have to add the focuslistener to the objects.
    scoreTextField.addFocusListener(new AutoSelect())

    By the way its much better to use focuslistener then mouselistener in this case. U will have autoselecteted text even with keyboard navigation.
    I hope u understand whats the difference between the way u implemented the focuslistener (through an adapter) and the actionListener.
    and why u used the button.addactionlistener(this)

    I was looking on a more elegant way to implement this behaviour to all my Objects on the form without extending every type of object, or
    add the focuslistener to every object.

Similar Threads

  1. JList with Vector for auto-suggest
    By nik_meback in forum AWT / Java Swing
    Replies: 0
    Last Post: December 31st, 2010, 03:56 AM
  2. Auto Email from excel or access
    By jj_bag in forum Java Theory & Questions
    Replies: 1
    Last Post: June 4th, 2010, 10:22 AM
  3. auto-increment of primary key
    By hundu in forum Enterprise JavaBeans
    Replies: 1
    Last Post: May 15th, 2010, 10:55 AM
  4. Auto Fill the TextField
    By malladiG in forum Java Theory & Questions
    Replies: 0
    Last Post: April 6th, 2010, 07:32 AM
  5. Auto contrast and auto brightness
    By oxxxis in forum Java Theory & Questions
    Replies: 0
    Last Post: January 21st, 2010, 03:00 PM