How to substitute a pressed char in Java - java

When a user presses the "dot" key on the keypad in a in a JTextField I'd like to transparently substitute it with a comma. I tried something like this:
jTextField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_DECIMAL) {
event.setKeyChar(',');
}
}
});
but it doesn't work.

Instead of trying to associate a new key with an already happened key event (this is impossible I think), you should try directly manipulating the text of the related JTextField instance via a call like yourTextField.setText(","); in the if statement of your code snippet above.

The sane way of replacing input in a TextField is to use a DocumentFilder on the TextField's Document (http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter).

Thank you all for your answers.
It's true that the better choice would be to write a document filter, but I need to substitute the dot character only if is pressed on the numpad, not when it comes from the regular keyboard.
I know I could set a flag in the keylistener and than read it in the documentfilter, but it sounds a bit too convoluted.
Thank you very much.
Franco

Here is my solution:
public class MyTextField extends JTextField {
private boolean substituteDot;
public MyTextField() {
super();
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent event) {
substituteDot = (event.getKeyCode() == KeyEvent.VK_DECIMAL);
}
#Override
public void keyTyped(KeyEvent event) {
if (substituteDot) {
event.setKeyChar(',');
}
}
});
}
}
Thank you all!
Bye
Franco

Related

Java calculator how to make backspace

I started learning programming a few days ago. I tried to make a calculator but i have one problem:
i don't know how to make backspace JButton.
buusun.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
tf.setText(text.getText().length()-1);
}
});
Any ideas?
Try this:
buusun.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
tf.setText(text.getText().substring(0, text.getText().length() - 1));
}
});
It uses the string.substring(start, end) method.
Note that you might need to adjust the exact variables you are using, as I'm not sure whether you need to get the value from tf or text, but this should provide the gist of what you want.

Java Key Press Event

I am trying to create a Bengali Keyboard using Java Swing. I am accessing key press event and replacing a particular character with relevant Bengali character. The problem I am getting is the original English character is still appending at the end. How to stop it? Here is the code.
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == 54)
{
textField.setText(textField.getText()+(char)2433);
}
if(e.getKeyCode() == 65)
{
textField.setText(textField.getText()+(char)2438);
}
}
The output is coming like "আa", should be only "আ".
Thanks in advance.
Here is the full Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Phonetic extends JFrame
{
public Phonetic()
{
setTitle("Antaryāmī");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setFont(new Font("Mukti Narrow", Font.PLAIN, 20));
textField.setBounds(12, 33, 614, 383);
getContentPane().add(textField);
textField.setColumns(10);
textField.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == 54)
{
textField.setText(textField.getText()+(char)2433);
}
if(e.getKeyCode() == 65)
{
textField.setText(textField.getText()+(char)2438);
}
}
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyReleased(KeyEvent e)
{
}
});
this.setSize(650, 450);
this.show();
}
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField textField;
public static void main(String args[])
{
new Phonetic();
}
}
Don't use a KeyListener.
Instead use a DocumentFilter. As text is inserted into the text field the DocumentFilter is invoked. At this time you should translate the typed character to the character that you want to insert into the Document and then invoke the super method. You will need to override both the insertString() and replace() methods.
Read the section from the Swing tutorial on Implementing a Document Filter for more information and an example to get your started.
just use this:
textField.setText((char)2433);
textField.getText()+(char)2433 appends the existing content of the TextField to the new character.
Edit in response to OP's comment:
It's more efficient to translate the user input on an event like a button click. Cause you'll confuse the user if as he/she enters a single letter you convert it to Bengali.
I mean you can wait until the user completes the word, then show the result, and if you need a real time translation (if we can call it so), a better option is to have a separate TextField and there you should say
translateTextField.setText(translateTextField.getText()+(char)2438);
while the event is raised on key press in the original TextField. I hope this is clear.
If you want to edit the code in place, try this: (Suppose convert is a method that converts all the string (s) and the character (e) and concatenate them)
public void keyPressed(KeyEvent e)
{
s = textField.getText();
textField.setText(convert(s, e.getKeyCode));
}

detect enter key in JTextField and do something in actionperformed

As i have seen many answers are too obscure for a entry level student like me.
i am following the steps by first addActionListner(this) to my JTextField.
what i am trying to do next and confuses the most is under:
public void actionperformed(Actionevent ae){
if(ae.getSource() == "Enter pressed")
{
outArea.setText(result);
}
}
which does not work because i feel like the code ae.getSource() == "Enter presses" is not working correctly and even i replaced the action i took under actionPerformed by a simple print line command like System.out.println("working"), it won't execute.
here is what i do if a button is pressed.
public void actionperformed(Actionevent ae){
if(ae.getSource() == "JButton")
{
System.out.println("JButton was pushed");
}
}
no matter how, lets say i have a GUI with a piece of given code like these:
public static void main(string[] args){
new myProg();
}
public myProg(){
....
buildTheGUI();
...}
}
//GUI Objects
...
JTextField input = new JTextField(10);
...
//method building the GUI
public void buildTheGUI(){
...
input.addActionListner(this);
...
//a method called actionPerformed
public void actionperformed(Actionevent ae){
}
i am now trying to detect the enter key by actionListner not by any other method because it's given.
Firstly, actionPerformed is triggerd by an action event, typically on most systems, this is triggered by the Enter key (with context to the JTextField)...so you don't need to check for it.
Secondly, the source of the ActionEvent is typically the control that triggered it, that would be the JTextField in this case.
Thirdly, String comparison in Java is done via the String#equals method...
if ("Enter presses".equals(someOtherString)) {...
Your actionPerformed method for the Button is wrong, try better this:
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton) {
JButton button = (JButton) e.getSource();
System.out.println("This button was pushed: " + button.getText());
}
}
And your for KeyListener try this to learn how it works:
#Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
System.out.println(e.getKeyCode());
}
Dont forget to let your class implement ActionListener and KeyListener.

Send Action to button who is listening for it

I have a JButton that has action listener.
btn_.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// DO STUFF
}
}
And I have a JSpinner that listens for key events.
spn_.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("Someone pressed enter key");
}
}
});
What I would like to do, is whenever user presses enter key while the spinner is selected, I would like it to execute whatever command the button does.
Yes I understand that I can simply have a function for the actions button does, and then execute the same function when user presses enter key. I am asking this because I am curious if it is possible for components in Swing to send actions to each other and how to do it rather than what is the correct way to program.
Yes I understand that I can simply have a function for the actions button does, and then execute the same function when user presses enter key. I am asking this because I am curious if it is possible for components in Swing to send actions to each other and how to do it rather than what is the correct way to program.
If you are implying that executing a function is the correct way, I would suggest that is not the best way to solve the problem.
The correct way is to share the Action, not the method that you invoke.
You should NOT be using a KeyListener at all in this solution. The general solution is to use Key Bindings. Read the Swing tutorial on How to Use Key Bindings for more information.
However, in your case it is even a little easier because you can just share the ActionListener:
ActionListener al = new ActionListner() {...}
JTextField editor = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
editor.addActionListener(al);
button.addActionListener(al);
Use doClick() method of JButton:
btn_.doClick()
Within keyPressed as following:
spn_.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
btn_.doClick()
}
}
});
The doClick() method as specified in oracle doc:
Programmatically perform a "click". This does the same thing as if the
user had pressed and released the button.
spn_.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
btn_.doClick(); // fires the actionPerfomed on the button
}
}
});

Clicking the textfield and clear the text?

Is it possible that when I clicked the textfield it would clear the recent text that was inputed there?. Mine was like, suppose these are textfields.
Name: Last Name First Name Middle Initial
Then I would click the Last Name and it would be cleared, same as First Name and Middle Initial. thanks for reading, hope you can help me.
Consider a FocusListener, one where all the text is selected:
myTextField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fEvt) {
JTextField tField = (JTextField)fEvt.getSource();
tField.selectAll();
}
});
By selecting all of the text, you give the user the option of either typing and thus deleting the current text and replacing it with the new text, or using the mouse or arrow keys to keep the current text and possibly change it.
I think Hovercraft is right. Better to use a FocusListener for this purpose.
I would write a utility class that could deal with this, I've done something similar for auto select. Means I don't have to extend every text component that comes along or mess around with lost of small focus listeners that do the same thing.
public class AutoClearOnFocusManager extends FocusAdapter {
private static final AutoClearOnFocusManager SHARED_INSTANCE = new AutoClearOnFocusManager();
private AutoClearOnFocusManager() {
}
public static AutoClearOnFocusManager getInstance() {
return SHARED_INSTANCE;
}
#Override
public void focusGained(FocusEvent e) {
Component component = e.getComponent();
if (component instanceof JTextComponent) {
((JTextComponent)component).setText(null);
}
}
public static void install(JTextComponent comp) {
comp.addFocusListener(getInstance());
}
public static void uninstall(JTextComponent comp) {
comp.removeFocusListener(getInstance());
}
}
Then you just need to use
JTextField textField = new JTextField("Some text");
AutoClearOnFocusManager.install(textField);
If you're just looking to supply a "prompt" (text inside the field that prompts the user), you could also look at the Prompt API
Why don't use the mouseClicked event?
So, you can have something like
jTextFieldMyText.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldMyTextMouseClicked(evt);
}
});
private void jTextFieldMyTextMouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldMyText.setText("");
}
In the case of focus
jTextFieldMyText.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldMyTextFocusGained(evt);
}
});
private void jTextFieldMyTextFocusGained(java.awt.event.MouseEvent evt) {
jTextFieldMyText.setText("");
}
If deleting text inmediatelly isn't what's wanted, use selectAll() instead of setText("") as suggested many times

Categories

Resources