简体   繁体   中英

Java Swing default focus on frame

I am learning java and Swing right now and trying to develop simple programms for education purposes.

So here is the question.

I have gridlayout and fields on my frame with default text

        accNumberField = new JTextField("0", 10);
    accNumberField.addFocusListener(new FocusListener() {
        int focusCounter = 0;
        @Override
        public void focusGained(FocusEvent arg0) {
            // TODO Auto-generated method stub
            if (focusCounter > 0)
            accNumberField.setText("");
            focusCounter++;
        }

What I want is that when user click on field for the first time the default text is disappered. So I add focus listener and used accNumberField.setText(""); in focusGained method.

But the problem is that for default first field in my frame getting focus right in time of frame creation. And default text is disappearing from the begining. I used counter as you can see. But that's not what I wanted.

I want that no field would get focus in time of creation and every field would be able to get focus from the time when user would click on one of them.

Sorry if I spelled something wrong. English is not my native language.

Is there any reason that you use focusListener()? why not use mouseListener() as follow?

    accNumberField.addMouseListener(new MouseAdapter()
    {
        @Override
        public void mouseReleased(MouseEvent e)
        {
            accNumberField.setText("");
        }
    });

if you want to clear the text for the first click, you can simply use a boolean:

    //outside constructor
    private boolean isTextCleared = false;

    //in constructor
    accNumberField.addMouseListener(new MouseAdapter()
    {
        @Override
        public void mouseReleased(MouseEvent e)
        {
            if (!isTextCleared)
            {
                accNumberField.setText("");
                isTextCleared = true;
            }
        }
    });

Found a thread having a code example of your desired functionality, Java JTextField with input hint . Precisely, you need to provide your own implementation of JTextField which will be holding the "default-text" in a field, specially created for that.

For your second question, you can set the focus to some button or frame itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM