How to delete text when a user clicks a JTextField? - java

In my program, the user writes something in a JTextField then clicks a 'generate' button, which triggers the characters in the JTextField to be drawn to a JPanel.
I would then like to clear all the text in the JTextField when the user clicks the JTextField again. I tried to achieve this by adding a FocusListener and an ActionListener to the JTextField, however my attempts did not work. Moreover, my implementation of the FocusListener gave an Unreachable Statement compiler error.
Is this possible to do in Java and if so how can I do this?
The code below is my ActionListener implementation.
dfaText = new JTextField(6);
dfaText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
generateLabel.setText("NOOOOO!!!");
dfaText.setText("");
isDfaDrawn = false;
canDraw = false;
repaint();
}
});

Add a mouse listener:
field.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
field.setText("");
}
});
Bear in mind this could get frustrating if the user legitimately clicks elsewhere and returns to the field. You may wish to maintain some state, e.g. only clear the field if the button has been clicked in the interim.

You can do this:
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField.setText("");
}
});

Just an addition to others' code.
public void textfieldMouseClicked(java.awt.event.MouseEvent evt) {
uname_tf.setText(null);
} //This will set the JTextfield blank on mouse click//
public void textfieldFocusLost(java.awt.event.FocusEvent evt) {
uname_tf.setText("Username");
} //This will bring back the default text when not in focus//
Hope it helps, Cheers!!!

If you want it just one Click on it to delete the text you can do like this :
textField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
textFieldMousePressed(evt);
}
});
private void textFieldMousePressed(java.awt.event.MouseEvent evt) {
textField.setText("");
}

Add 1 line to you buttonMethod e.g:
txtfield.clear();
or set your txtfield to an empty string

Related

Clear TextField on button press - Java Applet

I have a Java Applet for login form. It has 2 TextFields, username and password. I need to clear them on clicking Reset button. This is the code I have written.
public class LoginForm extends Applet implements ActionListener
{
TextField name, pass, hidden;
Button b1, b2;
public void init()
{
name = new TextField(20);
pass = new TextField(20);
b2 = new Button("Reset");
add(name);
add(pass);
add(b2);
b2.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString("Hello", 10, 150);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.setText("");
pass.setText("");
repaint();
}
}
But this is not working properly.
Once I click the Reset button, the actionPerformed() method gets called and it also calls repaint(). (I can see "Hello" being displayed).
But the TextFields do not get cleared.
If I make following changes in actionPerformed
name.setText(" "); // please note the spaces
pass.setText(" ");
then it works. But I don't want spaces there. I want the TextFields to get blank.
Any help is appreciated.
Probably it is not good solution, but this is a workaround.Before setting the text invoke getText method and it will reset. Pretty strange! This behaviour is marked as Bug on this page
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.getText();
pass.getText();
name.setText("");
pass.setText("");
repaint();
revalidate();
}
Another solution would be setting text with space. But not if you have password-like fields which have setEchoChar('*').
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.setText(" ");
pass.setText(" ");
repaint();
revalidate();
}
just put blank in text fields.
public void actionPerformed(ActionEvent e) {
name.getText();
pass.getText();
name.setText("");
pass.setText("");
repaint();
revalidate();
}

Does clicking on a JTextField call the actionPerformed method

I have multiple JTextFields and I want to see which one is selected within the program. At the moment it does not seem as though clicking on the JTextField calls an ActionEvent (is that how you phrase it?).
public void actionPerformed(ActionEvent ae){
if(e.getSource().equals(JTextField.class)){
current = (JTextField) e.getSource();
System.out.println(current);
}
}
A ActionListener will generally be triggered when the user "actions" the field, for most platforms/look and feels, this is triggered by the user pressing the Enter key.
I think what you're after is a FocusListener
Have a look at How to Write a Focus Listener for more details
If you just want to find out which component is currently focused, you could use the KeyboardFocusManager
Component focusedComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
Use can use addMouseListener too,
jtextField.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
...
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
Did you add the actionListener to the JTextFiled?
JTextField tf= new JTextfield();
tf.addActionListener(//class name goes there, if the actionListener is in a different class otherwise just say "this");

How to enable / disable buttons in java, eclipse?

How can I disable buttons with the press of one button and when the task that the button which has been pressed was assigned to has been done then I want all the buttons to be enabled. for example;
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Up Button");
}
});
DownButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Down Button");
}
});
LeftButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
UpButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Left Button");
}
});
RightButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
UpButton.setEnabled(false);
System.out.printline("Right Button");
}
});
I have tried to do it but it does not work. What I want is, for example, my Upbutton is printing out ("Up button"), so when a user presses this button I want all the other buttons to be disabled until it has finished doing the command that it was suppose to do, in this case print out a text but later on I will be adding things like adding up two user inputs e.g. I will have a button that will ask the user to type number 1 and then number 2 and then the computer will add them up and during this process I want all the buttons to be disabled expect the one that has been clicked on, until the user has given all numbers and the computer has given the output.
I hope I have explained myself properly, if not please let me know and I will try my best to give more information. Thanks in advance.
How about using Command objects? Each command object might have execute() and canExecute() methods at least. Then;
btnA.setEnabled( cmdA.canExecute() );
btnA.addActionListener( event-> {
cmdA.execute();
btnB.setEnabled( cmdA.canExecute() );
});
That seems right. Maybe you want them invisible instead of disabled...
In that case:
LeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setVisible(false);
UpButton.setVisible(false);
RightButton.setVisible(false);
System.out.printline("Left Button");
HereĀ“s an example of something that works:
private void jButtonChangeChampActionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxPlayer.setEnabled(true);
jComboBoxChampion.setEnabled(true);
jButtonSelecionar.setVisible(true);
jButtonMagias.setVisible(false);
}
What if you try this:
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpButtonActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Up Button");
}
It works here...
If you want to Set the Button Disabled , You can use the
btnExample.setDisable(true); // This will disable the Button
btnBreak.setVisible(false); // This will make the button Disappear visually only.
Hope this help guys.
You have to first disable the other buttons, finish your task and then enable the buttons again.
For example:
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// first disable all other buttons
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.println("Up Button");
// do rest of your tasks here.
// now enable them again
DownButton.setEnabled(true);
LeftButton.setEnabled(true);
RightButton.setEnabled(true);
}
});
Similarly, setup the Listeners for the other buttons.
Hope this helps!

How to "ignore/discard" Swing UI events when doing data validations on UI?

There's a text field and when lost focus it will validate the inputs, if not passed, print out the error message (to be simple here just has an empty check). And there's a button next to the text field, it will print out the text once click on it.
As I tried, when input some text and then click the button it will trigger both the focus lost event of text field and the event of button. In a other word, it will do the validation first and then print out the input text.
Here comes my question, what is the good approach to prevent printing out the text if the validation not passed? Or is there a way to "ignore" the click event on button if validation not passed?
I tried to use a boolean flag which indicate the validation result and check the flag when perform the action for button, but I do not think it is a good approach. As I know there's an event dispatcher thread in Swing which deal with the events, is it possible I can cancel the events from here?
Below is a piece of code which explain the question:
public class SimpleDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel(new FlowLayout());
frame.setContentPane(content);
final JTextField textField = new JTextField(10);
textField.addFocusListener(new FocusAdapter()
{
#Override
public void focusLost(FocusEvent e)
{
String text = textField.getText();
// do some validation here, if not validated
// do not trigger the event on button.
if ("".equals(text))
{
System.out.print("please input a text!");
}
}
});
content.add(textField);
JButton button = new JButton("Print Text");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// action performed for button
String text = textField.getText();
System.out.println(text);
}
});
content.add(button);
frame.setVisible(true);
frame.pack();
}
}
I faces similar issue while working on an application. I solved it like below
I created a abstract class ApplicationFrame which every frame in the application extends
public abstract class ApplicationFrame extends JFrame implements ActionListener {
#Override
final public void actionPerformed(ActionEvent event) {
if(validateInput()){
performAction(event);
}
}
/*
* Sub class should override this method to receive any action
*/
protected void performAction(ActionEvent event) {};
/*
* Sub class should override this method to perform validation
*/
abstract protected boolean validateInput();
}
All Frames will now extend this base frame, as below:
public class Frame1 extends ApplicationFrame{
#Override
protected void performAction(ActionEvent event) {
// perform action
}
#Override
protected boolean validateInput() {
// return true or false depending upon the validation results
}
// if you want to add Action Listener, you need to add like this:
btnSomeButton.addActionListener(this);
}
If you need to handle Focus events, you can make ApplicationFrame or the base frame implement FocusListener.
This is my custom implementation to solve the problem, hope this helps.
Make the button disabled on start-up
Upon lost focus, validate the text & enable button only when the input passes validation.
Upon start of text change, disable the button
It's always makes sense to make ui to communicate with user. So you can show "please input a text" as the default text of the textField when nothing is entered by user.
Here is the code for such custom textField:
public class TextFieldWithDefaultText extends JTextField implements FocusListener{
private final String hint;
public TextFieldWithDefaultText (String $text)
{
super($text);
this.hint = $text;
addFocusListener(this);
}
#Override
public void focusGained (FocusEvent $e)
{
if (this.getText().isEmpty())
{
super.setText("");
}
}
#Override
public void focusLost (FocusEvent $e)
{
if (this.getText().isEmpty())
{
super.setText(hint);
}
}
#Override
public String getText ()
{
String typed = super.getText();
return typed.equals(hint) ? "" : typed;
}
}
Write the acttionListerner for your button like this:
JButton button = new JButton("Print Text");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(!textField.getText().isEmpty())
System.out.println(textField.getText());
}
});
And ur textField implementation should be :
final TextFieldWithDefaultText textField = new TextFieldWithDefaultText ("please input a text");
Hope this helps :)

JLabel on change text event

How I can retrive the event on a JLabel when change the text inside??
I have a JLabel and when change the text inside I have to update other field.
techically, the answer is to use a PropertyChangeListener and listen to changes of the "text" property, something like
PropertyChangeListener l = new PropertyChangeListener() {
public void propertyChanged(PropertyChangeEvent e) {
// do stuff here
}
};
label.addPropertyChangeListener("text", l);
not so technically: could be worth to re-visit the overall design and bind to original source which triggered the change in the label
IMHO you can not get an event on JLabels textchange. But you can use a JTextField instead of a JLabel:
private JTextField textFieldLabel = new JTextField();
textFieldLabel.setEditable(false);
textFieldLabel.setOpaque(true);
textFieldLabel.setBorder(null);
textFieldLabel.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate(DocumentEvent e) {
System.out.println("removeUpdate");
}
public void insertUpdate(DocumentEvent e) {
System.out.println("insertUpdate");
}
public void changedUpdate(DocumentEvent e) {
System.out.println("changedUpdate");
}
});
Note: this event is fired no matter how the text gets changed; programatically via "setText()" on the TextField or (if you do not "setEditable(false)") via clipboard cut/paste, or by the user typing directly into the field on the UI.
The lines:
textFieldLabel.setEditable(false);
textFieldLabel.setOpaque(true);
textFieldLabel.setBorder(null);
are used to make the JTextField look like an JLabel.

Categories