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));
}
}
});
Related
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());
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
Let me describe little bit whats my situation,
I have SWT Text in my Java SE SWT application:
let say USER will write something (String) to the created Text while app running. I would like to introduce some MouseListener which would do exactly this:
When USER would click into Textobject/widget, this Text would clear(setText("");) itselves(if there was previously written some String).
MouseListener has 3 methods: mouseDown(...), mouseUp(..), mouseDoubleClick(...) -> I should use onlymouseDown(...) in this case - nothing more isnt nescesary.
In mouseDown(..) method I would need to call method of actual Text object reference : "XY".setText(""); Text which was clicked-into by mouse. -> This I somehow could not obtain.
I would like to have it somehow like general MouseListener onMouseClickText which could be applied to any SWT Text I will use in my app.
Does anybody know how to do such MouseListener or better : how to obtain this reference to existing clicked SWT Text, inside MouseListener?
here is example code:
package sk.tokra.example;
//imports here
.
.
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
.
.
public class Application {
//class fields
Text text;
private static final Logger logger = LoggerFactory.getLogger(Application.class);
.
.
.
// main
public static void main(String[] args) {
logger.debug("main(), Starting app!");
try {
Application window = new Application();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
logger.debug("main(), Exiting app!");
return;
}
/**
* Open the window.
*/
public void open() {
logger.debug("open()");
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
text = new Text(shell, SWT.BORDER);
text.addMouseListener(onMouseClickText);
.
.
.
}
//other stuff/methods/listener part
private MouseListener onMouseClickText = new MouseListener() {
#Override
public void mouseUp(MouseEvent arg0) {
logger.debug("onMouseClickFind, mouseUp()");
}
#Override
public void mouseDown(MouseEvent arg0) {
logger.debug("onMouseClickFind, mouseDown()");
// HERE I WOULD NEED to obtain refence of Text
// then call .setText("");
}
#Override
public void mouseDoubleClick(MouseEvent arg0) {
logger.debug("onMouseClickFind, mouseDoubleClick()");
}
};
}
As Naveen suggested it is much better to you use a focus listener because the same text widget can receive focus through numerous different ways (like tabbing on keyboard). You might want to handle that case as well.
In any case, whether you use a FocusListener or MouseListener on the Text, you can fetch the widget which actually caused the event. In case of the mouse listener you receive an instance of MouseEvent and you can use MouseEvent#widget to access the Text control. Your code would look something like below in the listener implementation:
//other stuff/methods/listener part
private MouseListener onMouseClickText = new MouseListener() {
#Override
public void mouseUp(MouseEvent arg0) {
((Text) arg0.widget).setText("");
}
...
}
You may add the same listener instance to multiple Text widgets, it should work.
is it possible in java to have a class where it has EventHandlers for with different functions? for example button1 will log you in, while button2 will log you out, is this possible? Here's the code I made it seems to be not working.
package event.handlers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TheHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent logInEvent) {
System.out.println("Button Login");
}
public void actionPerformed(ActionEvent cancelEvent) {
System.out.println("Cancel Login");
}
}
You either need two implementations of ActionListener, one for each button or the actionPerformed needs to determine the button by the event argument and take the appropriate action. Your code will not compile because the signatures for both methods are the same.
No. You can not have a class implement two methods with the same function signature. How would the compiler know which one to call for different events? The name you give to the arguments has no meaning to the compiler.
As an alternative, you can create multiple anonymous action listeners that simply forward the call to a method that does have a unique name if you want everything to be in the same class.
public class TheHandler {
public TheHandler() {
JButton login, cancel;
//initialize code here
login.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent logInEvent) {
loginPerformed(logInEvent);
}
});
cancel.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent cancelEvent) {
cancelPerformed(cancelEvent);
}
});
}
public void loginPerformed(ActionEvent logInEvent) {
System.out.println("Button Login");
}
public void cancelPerformed(ActionEvent cancelEvent) {
System.out.println("Cancel Login");
}
}
You may use getSource() or getActionCommand() method of ActionEvent.
#Override
public void actionPerformed(ActionEvent logInEvent) {
Object src=logInEvent.getSource();
String cmd=logInEvent.getActionCommand(); //It will return caption of button
if(src==btn1)
{
//
}
//Or
if(cmd.equals("Button1")) { ... }
}
You can not have multiple actionPerformed method in one class. Simple way is to do operation based on source of action like:
(in actionPerformed method)
if(e.getSource() == loginButtton) { // based on button variable if they are in same class and accessible in actionPerformed method
loginMethod()
} else if(e.getSource == logoutButton) {
logoutMethod()
}
or
if(e.getActionCommand().equals("loginButtton")) { // based on caption/text on button
loginMethod()
} else if(e.getActionCommand().equals("logoutButtton")) {
logoutMethod()
}
or you can have different anonymous class for different buttons like
loginButton.addActionListner(new ActionListerner(){
public void actionPerformed(ActionEvent loginEvent) {
loginMethod();
}
});
logoutButton.addActionListner(new ActionListerner(){
public void actionPerformed(ActionEvent cancelEvent) {
logoutMethod();
}
});
The problem there is that your two method signatures are identical. When Java tries to figure out which method to call, it can't tell the difference between the two.
I can think of two ways to do what you want:
Presumably, you are registering the listeners on the buttons like cancelButton.addActionListener(...). So you can either provide each button with its own anonymous inner class:
loginButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent logInEvent) {
System.out.println("Button Login");
}
}
cancelButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent cancelEvent) {
System.out.println("Cancel Login");
}
}
or you can define a single actionPerformed method that checks the source of the call:
public class TheHandler implements ActionListener {
JButton loginButton;
JButton cancelButton;
public TheHandler()
{
...
// Now, technically, this is bad form because you're leaking 'this'.
// But as long as this will only be called after this constructor finishes
// initializing, it's safe.
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
...
}
...
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == loginButton)
System.out.println("Button Login");
else if(evt.getSource() == cancelButton)
System.out.println("Cancel Login");
}
}
Using anonymous inner classes can sometimes be clearer, because you see the code right next to the addListener call, but it also adds a lot of boilerplate, and if you're working on a very large progect that can take a while to load, reducing the number of classes can sometimes make it load a little faster (each anonymous inner class is another thing for the JVM to load).
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.