How to Unfocus a Jtextfield

How to UnFocus a JTextField

A log-in would be best done in a modal dialog, but that introduces problems in that the method requestFocusInWindow() must be called after the component is visible, but that is blocked by the fact the dialog is modal!

This example uses Rob Camick's RequestFocusListener (as presented in Dialog Focus) to manage focus after the dialog is visible.

Login with focused password field

Note: That is how it appears before the user does anything. The password field is focused by default.

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

public class LoginRequired {

LoginRequired() {
JFrame f = new JFrame("Login Required");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

f.setResizable(false);
f.setSize(400, 300); // not recommended, but used here for convenience
f.setLocationByPlatform(true);
f.setVisible(true);

showLogin(f);
}

private void showLogin(JFrame frame) {
JPanel p = new JPanel(new BorderLayout(5,5));

JPanel labels = new JPanel(new GridLayout(0,1,2,2));
labels.add(new JLabel("User Name", SwingConstants.TRAILING));
labels.add(new JLabel("Password", SwingConstants.TRAILING));
p.add(labels, BorderLayout.LINE_START);

JPanel controls = new JPanel(new GridLayout(0,1,2,2));
JTextField username = new JTextField("Joe Blogs");
controls.add(username);
JPasswordField password = new JPasswordField();
password.addAncestorListener(new RequestFocusListener(false));
controls.add(password);
p.add(controls, BorderLayout.CENTER);

JOptionPane.showMessageDialog(
frame, p, "Log In", JOptionPane.QUESTION_MESSAGE);
System.out.println("User Name: " + username.getText());
System.out.println("Password: " + new String(password.getPassword()));
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new LoginRequired();
});
}
}

/**
* Convenience class to request focus on a component.
*
* When the component is added to a realized Window then component will
* request focus immediately, since the ancestorAdded event is fired
* immediately.
*
* When the component is added to a non realized Window, then the focus
* request will be made once the window is realized, since the
* ancestorAdded event will not be fired until then.
*
* Using the default constructor will cause the listener to be removed
* from the component once the AncestorEvent is generated. A second constructor
* allows you to specify a boolean value of false to prevent the
* AncestorListener from being removed when the event is generated. This will
* allow you to reuse the listener each time the event is generated.
*/
class RequestFocusListener implements AncestorListener
{
private boolean removeListener;

/*
* Convenience constructor. The listener is only used once and then it is
* removed from the component.
*/
public RequestFocusListener()
{
this(true);
}

/*
* Constructor that controls whether this listen can be used once or
* multiple times.
*
* @param removeListener when true this listener is only invoked once
* otherwise it can be invoked multiple times.
*/
public RequestFocusListener(boolean removeListener)
{
this.removeListener = removeListener;
}

@Override
public void ancestorAdded(AncestorEvent e)
{
JComponent component = e.getComponent();
component.requestFocusInWindow();

if (removeListener)
component.removeAncestorListener( this );
}

@Override
public void ancestorMoved(AncestorEvent e) {}

@Override
public void ancestorRemoved(AncestorEvent e) {}
}

Unfocus on all JTextFields

The reason why I would like to not focus on the JTextFields is to avoid the hints from not appearing when the application first loads

Text Prompt can support this requirement (ie. the prompt will disappear only when text is entered). Then you don't have to worry if the text field has focus or not.

How do i change the focus to be on a different field, such as a JButton?

You would use requestFocusInWindow() on the component AFTER the GUI is visible. But this doesn't make sense since the user would need to tab backwards to get to the text field. Or you could use the RequestFocusListener found in Dialog Focus. Again remember advanced users don't use the mouse.

Remove Focus from JTextfields

From How to use the focus subsystem we get the following:

If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed. The following sample code shows how this operation can be done:

//...Where initialization occurs...
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel(new BorderLayout());

//...Create a variety of components here...

//Create the component that will have the initial focus.
JButton button = new JButton("I am first");
panel.add(button);
frame.getContentPane().add(panel); //Add it to the panel

frame.pack(); //Realize the components.
//This button will have the initial focus.
button.requestFocusInWindow();
frame.setVisible(true); //Display the window.

How to disable automatic focus on textField

As discussed in the comments, I added a radio button to take the focus instead:

public class Main extends JFrame {

JTextField textFieldKwotaWplacona, textFieldOprocentowanie;

Main() {

setTitle("Program do liczenia procentu składanego");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

textFieldKwotaWplacona = new JTextField("Ilość pieniędzy wpłaconych");
textFieldKwotaWplacona.setForeground(Color.decode("0x8C8C8C"));
textFieldKwotaWplacona.addFocusListener(new FieldFocusListener(textFieldKwotaWplacona));
add(textFieldKwotaWplacona);

textFieldOprocentowanie = new JTextField("Oprocentowanie");
textFieldOprocentowanie.setForeground(Color.decode("0x8C8C8C"));
textFieldOprocentowanie.addFocusListener(new FieldFocusListener(textFieldOprocentowanie));
add(textFieldOprocentowanie);

JRadioButton btn = new JRadioButton("text");
add(btn);

pack();
btn.requestFocusInWindow();
}

private class FieldFocusListener extends FocusAdapter {

private JTextField field;

FieldFocusListener(JTextField field) {

this.field = field;
}

@Override
public void focusGained(FocusEvent e) {

if (field.getForeground() != Color.BLACK) {
field.setText("");
field.setForeground(Color.BLACK);
}
}
}

public static void main(String[] args) {

Main a = new Main();
a.setVisible(true);
}
}

Explanation

From the tutorial:

If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed.

That means btn.requestFocusInWindow() must appear after pack() and before a.setVisible(true).

The reason you need another component to take the focus is that when a window is focused, a component inside it must gain the focus.

Notes:

  • If you want a better text field hint, see @camickr's answer.
  • Don't use null layout. Pick one that serves your GUI design (I picked FlowLayout just because it's fast to use, though probably not what you need).
  • Instead of setting the size of the frame, pack() after all components had been added.
  • Instead of creating the same focus listener for every text field, just create it as a class and reuse it. I show one way with passing the component to a constructor, but you can get rid of that and use e.getComponent() to get the text field instance.

how to unfocus a textfield in flutter

Have you tried readonly
property, readonly will still gain focus and will block keyboard connection preventing it from popping up.

 TextField(
readOnly:true
controller: editingController,
onTap: () async {
selectedValue = await showDialog();
setState(() {
editingController.text = '$selectedValue';
});
},
);

source :issue:16863

How to unfocus TextFiled When id dismis the keyboard in flutter

I think I found a working solution, (currently only tested on android emulator).

This is a small working example:

import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);

@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
late FocusNode node;

@override
void initState() {
super.initState();
node = FocusNode();
}

@override
void dispose() {
node.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Focus Demo'),
actions: [
TextButton(
onPressed: () {
node.unfocus();
WidgetsBinding.instance?.addPostFrameCallback((_) {
FocusScope.of(context).requestFocus(node);
});
},
child: Text(
'Focus',
style: Theme.of(context).primaryTextTheme.bodyText1,
),
),
],
),
body: TextField(
focusNode: node,
),
),
);
}
}

I was able to get it working by adding a delay between the unfocusing and refocusing using WidgetsBinding.instance?.addPostFrameCallback.

In your case that should translate to something like this:

  onTap: () {
controller.textFieldFocus.unfocus();
WidgetsBinding.instance?.addPostFrameCallback((_) {
FocusScope.of(context).requestFocus(controller.textFieldFocus);
});
},

Want jTextField to lose focus when I click on the main window

Why do you want to lose focus? I'm sure there is better design then to force the user to click on the window to cause the text field to lose focus.

Anyway, the text field will lose focus when another component gains focus. By default a panel is not focusable so clicking on it will not cause the text field to lose focus. Make the panel focusable:

panel.setFocusable( true );

Of course now when the user uses the tab key, the panel will now be included in the tab order. Thats another reason this seems like a bad design.

How to unfocus text field in flutter?

Sample Image

Wrap your full page in GestureDetector and modify it's onTap function as follows:

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () { //here
FocusScope.of(context).unfocus();
new TextEditingController().clear();
},
child: Container(
...
);
}


Related Topics



Leave a reply



Submit