How To Register A Key Listener In Java Apple Utilities
In this small Swing code snippet we demonstrate how to employ java.awt.event.KeyAdapter
abstract class to handle keyboard event for the JTextField
component. The snippet will change the characters typed in the JTextField
component to uppercase.
A amend arroyo for this utilize case is to utilise the DocumentFilter
class. Run into the following code snippet How do I format JTextField text to uppercase?.
package org.kodejava.swing; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import java.awt.Dimension; import coffee.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.event.KeyAdapter; import coffee.awt.event.KeyEvent; public form UppercaseTextFieldDemo extends JFrame { public UppercaseTextFieldDemo() throws HeadlessException { initComponents(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new UppercaseTextFieldDemo().setVisible(truthful)); } protected void initComponents() { // Set default form size, endmost event and layout director setSize(500, 500); setTitle("JTextField Key Listener"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); // Create a label and text field for our demo application and add the // component to the frame content pane object. JLabel usernameLabel = new JLabel("Username: "); JTextField usernameTextField = new JTextField(); usernameTextField.setPreferredSize(new Dimension(150, 20)); getContentPane().add(usernameLabel); getContentPane().add together(usernameTextField); // Register a KeyListener for the text field. Using the KeyAdapter class // allow us implement the only primal listener outcome that we want to listen, // in this instance we use the keyReleased consequence. usernameTextField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent east) { JTextField textField = (JTextField) e.getSource(); String text = textField.getText(); textField.setText(text.toUpperCase()); } }); } }
- Author
- Contempo Posts
How To Register A Key Listener In Java Apple Utilities,
Source: https://kodejava.org/how-do-i-add-key-listener-event-handler-to-jtextfield/
Posted by: bellladjecamis.blogspot.com
0 Response to "How To Register A Key Listener In Java Apple Utilities"
Post a Comment