JLabel on change text event - java

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.

Related

How do i get the value in the textfield in GUI? java

I also wanted to make the input dynamic so that it changes the value as i press any key. Thanks i dont know how to use a keylistener or something that would process my code.
public static void DecimalToAll(String varInput){
//DeciToHexa
int varDeciToHexa = Integer.parseInt(varInput);
String DeciToHexaAnswer = Integer.toHexString(varDeciToHexa);
System.out.println(DeciToHexaAnswer.toUpperCase());
//DeciToOctal
int varDeciToOctal = Integer.parseInt(varInput);
String DeciToOctalAnswer = Integer.toOctalString(varDeciToOctal);
System.out.println(DeciToOctalAnswer);
//DeciToBinary
int varDeciToBinary = Integer.parseInt(varInput);
String DeciToBinaryAnswer = Integer.toBinaryString(varDeciToBinary);
System.out.println(DeciToBinaryAnswer);
An example making use of DocumentListener:
JTextField can't add a "ChangeListener" like other components. To "monitor' changes in a JTextField, you can add a DocumentListener to the textfield:
private class MyDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e){
//Do nothing
}
public void insertUpdate(DocumentEvent e){
//Do things when text are inserted
}
public void removeUpdate(DocumentEvent e){
//Do things when text are deleted
}
}
To add the DocumentListener, get the Document object from JTextField and add it:
JTextField txt = new JTextFeld();
txt.getDocument().addDocumentListener(new MyDocumentListener());

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");

Focus Gained and Focus Lost Java

I have some text field on my form. And I like focusGained and focusLost event. Doing this with 2 or 3 text field is easy. But, after 18 text field, well, it's kinda confusing.
Is there any way to shorten the focusGained and focusLost event?
Example:
txtSomeTextFocusGained(java.awt.event FocusEvent evt){
if(txtSomeText.getText().equals("Text here!"){
txtSomeText.setText("");
}
}
txtSomeTextFocusLost(java.awt.event FocusEvent evt){
if(txtSomeText.getText().equals(""){
txtSomeText.setText("Text here!");
}
}
That's one text field, I've problem handling with about 18 text field. Any way to simplify that?
Thanks.
The methods are simple enough, so I can't think of a way to simplify them any further. What you can do, though, is prevent code repetition by declaring one FocusListener instance and then add it using addFocusListener(...) to all text-fields.
It would look something like this:
// Instantiate a FocusListener ONCE
java.awt.event.FocusListener myFocusListener = new java.awt.event.FocusListener() {
public void focusGained(java.awt.event.FocusEvent focusEvent) {
try {
JTextField src = (JTextField)focusEvent.getSource();
if (src.getText().equals("Text here!") {
src.setText("");
}
} catch (ClassCastException ignored) {
/* I only listen to JTextFields */
}
}
public void focusLost(java.awt.event.FocusEvent focusEvent) {
try {
JTextField src = (JTextField)focusEvent.getSource();
if (src.getText().equals("") {
src.setText("Text here!");
}
} catch (ClassCastException ignored) {
/* I only listen to JTextFields */
}
}
};
(You could omit the try-catch blocks if you were absolutely sure that the source of the event would always be a JTextField, but it is always a bad practice to rely on such assumptions.)
Then, for every JTextField you only need to add the same FocusListener:
...
someTextField.addFocusListener(myFocusListener);
...
(It's only half a line - difficult to get any shorter than that.)
Another alternative would be to subclass JTextField, adding a FocusListener in the constructor, but I don't see any advantage over the first solution (unless you want a more flexible/powerful solution, e.g. different text for each JTextField etc).
If you want just to set some text in field which gets focused you could write separated event handler class which implements FocusListener and then override focusGained and focusLost methods. Something like this:
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class CustomFocusListener implements FocusListener {
JTextField txt;
String textWhenFocusGained;
String textWhenFocusLost;
public CustomFocusListener(JTextField txt, String textWhenFocusGained,
String textWhenFocusLost) {
this.txt = txt;
this.textWhenFocusGained = textWhenFocusGained;
this.textWhenFocusLost = textWhenFocusLost;
}
#Override
public void focusGained(FocusEvent arg0) {
txt.setText(textWhenFocusGained);
}
#Override
public void focusLost(FocusEvent arg0) {
txt.setText(textWhenFocusLost);
}
}
Use this.
if(txtSomeText.getText().equals("Text here!")){
txtSomeText.setText("");
/////////////// It's problem of lower and supper case you should make ur text in lower case in code. and for desing of jtextfield it's ok
txtIdDeVoyageur = new JTextField();
txtIdDeVoyageur.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
if(txtIdDeVoyageur.getText().trim().toLowerCase().equals("id de voyageur")){
txtIdDeVoyageur.setText("");
txtIdDeVoyageur.setForeground(Color.black);
}
}
#Override
public void focusLost(FocusEvent e) {
if (txtIdDeVoyageur.getText().trim().equals("") ||
txtIdDeVoyageur.getText().trim().toLowerCase().equals("id de voyageur"))
{
txtIdDeVoyageur.setText("id de voyageur");
txtIdDeVoyageur.setForeground(new Color (153,153,153));
}
}
});

How to delete text when a user clicks a JTextField?

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

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 :)

Categories