action listening for a JFrame - java

I am trying to listen tab-in tab-out action for my swing gui that is made by JFrame. I have a JTextField added to the JFrame that will be getting the user clipboard whenever the window is selected so the user may tab between programs, copy some url so when back to my program, this JTextField will be populated by the copied url string.
EDIT:
I have tried this:
frame.addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) {
url= getClipboardData();
}
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
}
);
it doesnt work

A frame doesn't recieve a focus event. A component on the frame gets the focus event.
If you want to know when a frame gets focus then use a WindowListener and handle the windowActivated event.

What you want is a FocusListener not an ActionListener. Check out the java Doc and you'll know how to use it. It's easy.

it looks like you are not setting the clipboard data onto the text field.
frame.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
getJTextField().setText(getClipboardData());
}
public void focusLost(FocusEvent e) {
//ignored
}
});
Something like that will likely solve your problem

Related

Handling exit button which is create automatically?

I am building a text editor and I don't know how to handle a listener on Swing exit button, which is create automatically.
I want to use dialogs when user doesn't save file, for example press exit button.
final JFrame f = new JFrame("Good Location & Size");
// make sure the exit operation is correct.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we) {
// pop the dialog here, and if the user agrees..
System.exit(0);
}
});
As seen in this answer to Best practice for setting JFrame locations, which serializes the frame location & size before exiting.
Assuming you have a handle on your window, assuming it's a Window object (e.g. a JFrame or other kind of window), you can listen to WindowEvent events. Here is an example with windowClosed, you can replace it with windowClosing if you need to intercept it before.
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
// do something here
}
});
Go stepwise:
Declare a boolean variable saved and set its default value to false.
When user saves the file, change it to true
When exit button is pressed, check the variable.
If true, exit, else, prompt user for saving file.
So, finally this code snippet looks like:
public boolean saved = false;
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saved = true;
//Code to save file
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(saved)
System.exit(0);
else {
//Code to prompt user to save file
}
}
});

Java - How to "unhide" a JFrame

I am quite new to Java, but familiar with native Android dev so bear with me xD. I created an application that creates a JFrame. Then I set the closeOperation to: setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);.
It performs as expected, the frame is hidden and this is what I want (when I close). I need the application to keep on running (only once instance), because I am running a thread in the background that is performing an operation.
My actionListener on my button in my JFrame currently does this: setVisible(false);
My question is this, how can I maximize the JFrame again after it has been hidden? Would it be possible to display the frame when the user clicks on the minimized application in the task bar? Is there some type of listener that I need to implement?
Thanks in advance, any advice will be appreciated
UPDATE
For this solution to work correctly you need to do the following. Also have a look at XtremeBaumer's answer for this to make sense.
On JFrame creation setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);.
When you want to minimize the app (on click possibly) frame.setState(Frame.ICONIFIED);.
When you want to maximize the app again frame.setState(Frame.NORMAL); in windowDeiconified event.
One last thing, if you want to also minimize your app when the user clicks on the exit button (red x) add this to the windowClosing event frame.setState(Frame.ICONIFIED);.
this.addWindowListener(new WindowListener(){
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
setState(Frame.ICONIFIED)
}
#Override
public void windowDeactivated(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
this.setVisible(true);
//this should be what you want
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowOpened(WindowEvent e) {
}
});
i hope this solves your question. add it to your JFrame

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 can I Listen for Keyboard input without Text Field Java

I am working on a Java application and interfacing with an RFID reader that acts as a keyboard input device.
The application will be used for employee time tracking, so the employee should not see the code that his/her RFID tag contains.
Currently, the application opens a jFrame that asks the employee to scan their tag. This is where I would like to listen for the keyboard input.
All of the RFID tags are 10 digits, so I would like to use some kind of regex to detect when a card is scanned if possible.
If someone could point me in the right direction, or contribute some code I would be grateful.
Thanks in advance.
UPDATE:
I was able to read the input of the scanner by adding the following to the constructor of my JFrame.
addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){ System.out.print(e.getKeyChar());}
#Override
public void keyReleased(KeyEvent e) { }
#Override
public void keyTyped(KeyEvent e) { }
});
So it is now confirmed that the Reader is just standard Keyboard input.
Here is an example of what I get for a tag: 0006459027
Now, the big question is, how do I take the characters that I got, and detect that it is a 10 digit string, and from there trigger an event to open a new frame?
First, I'd see if the RFID reader is triggering an ActionEvent to be fired when the tag is scanned. This would be the simplest approach.
Failing that, you would need to attach a DocumentListener to the fields underlying document and monitor for changes.
You'll need to decide how best to interrupt the results (as you're likely to get each letter of the RFID at a time). You could monitor the length of the document or have a javax.swing.Timer which triggers after a short delay (you'd reset the timer on each update event triggered by the DocumentListener)
Check out
JTextField.addActionListener
JTextField.getDocument().addDocumentListener
I'd suggest taking a look at DocumentFilter as well, but your interested in the final result, not modifying it.
UPDATED with DocumentListener Example
// In the classes variable decleration section...
private JTextField rfidField;
// In the classes constructor or UI init method...
rfidField = new JTextField(12);
rfidField.getDocument().addDocumentListener(new DocumentListener() {
public void handleUpdate(DocumentEvent e) {
if (e.getDocument().getLength() == 10) {
System.out.println("Trigger me happy...");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
rfidField.setText(null);
}
});
}
}
#Override
public void insertUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
handleUpdate(e);
}
});
// Now don't forget to add the field to your forms container ;)
//////
One of things I would be do when you "trigger" the code event is, once you've read it from the text field, is clear the text field (JTextField.setText(null)) - IMHO
If the RFID reader acts as a keyboard input device, try with key events:
JFrame frame = new JFrame();
// frame setup
frame.addKeyListener(new KeyAdapter(){
public void KeyPressed(KeyEvent ke)
{
System.out.println(ke);
}
});
Otherwise you have to check which kind of event it fires.
I was in a similar situation but with a bar-code scanner.
I really worked hard on a custom DocumentListener that would take care of all scenarios, and none of it worked.
Out of desperation, I added an ActionListener and it then worked very well.
Here is a code snap-shot :
try {
txtStockItemRef.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(txtStockItemRef.getText());
DatabaseManager.peformStockItemLookupByBarcodeRef(txtStockItemRef.getText());
}
});
} catch(Exception exc) {
LiveCityRetailTools.handleExceptionWithUserMessage(exc);
}

Java KeyListener not firing on JSpinner

have tried a few different approaches to this but with no success so far. Just wondered if I'm missing anything. I have a JSpinner which is a component of a DateSelector widget alongside a Calendar. I am trying to fire a validation method if the user changes any text in the JSpinner instead of using the Calendar control or the JSpinner up and down arrows.
Here are the different approaches I have tried:
jSpinner1.addKeyListener(kl);
jSpinner1.getEditor().addKeyListener(kl);
((JSpinner.DefaultEditor) jSpinner1.getEditor().getTextField().addKeyListener(kl);
Anyone out there got any ideas as to what I'm doing wrong? Thanks
UPDATE
Apologies, I should have said that I have already added a ChangeListener to the JSpinnerDateModel which is attached to the JSpinner. Like so:
ChangeListener changeListener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
dateChanged();
}
};
jSpinnerDateModel.addChangeListener(changeListener);
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
dateChanged();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
};
((JSpinner.DefaultEditor) jSpinner1.getEditor()).getTextField().addKeyListener(
keyListener);
Thanks
Frank
If you want to disable keyboard editing do this:
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
tf.setEditable(false);
To listen for key events you need to add a listener to the text field. This works for me:
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("PRESSED!");
}
#Override
public void keyTyped(KeyEvent e) {
}
});
JSpinners handle KeyEvents themselves, but they fire ChangeEvents to the outside world. Adding a ChangeListener should allow you to perform the validation you wish.
See also: Detecting Spinner Value Changes (Java Tutorials)
This is a shortfall of swing, and in my opinion JSpinner should follow JComboBox in supplying the following access to the underlying text field:
JComboBox.getEditor().getEditorComponent()
From going through the source of J1.7 I found you can acheive pretty much the same thing with
JSpinner.getEditor().getComponent(0)
Therefore you can "hack" the listener in the following way:
JSpinner.getEditor().getComponent(0).addKeyListener(...)
Obviously this depends on the 'under the covers' implementation of swing and works as at J1.7 but there is no guarantee this works for other versions future or past.
Enjoy.
EDIT
or if the editor is an instance of DefaultEditor, you can cast it as such and use 'getTextField()'. It would be handy if this were defined in the interface.

Categories