I have a panel just with a Jtextfield that only accept numbers. So, when I press enter will load a user profile. this is just to see his profile.
What I want: When I press ENTER again all the profile will be cleared, and when I press the numbers and press ENTER again and load the profile again and again...
My problem: I pressed enter and the profile is cleared (Ok all fine), but when I enter the number and press the ENTER, The numbers are cleared and nothing happens, it is like a loop in matriculaTxt.addKeyListener(new KeyAdapter() { ... }
Sorry for my bad English.
private void matriculaTxtActionPerformed(java.awt.event.ActionEvent evt)
{
String matricula = matriculaTxt.getText().trim();
if (!matricula.matches("[0-9]+")) {
matriculaTxt.setText("");
} else {
fc = new FrequenciaController();
matriculaTxt.setEditable(false);
matriculaTxt.requestFocus();
fc.checkinManual(Integer.parseInt(matricula));
}
// the problem is here.
matriculaTxt.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
nomeTxt.setText("");
statusTxt.setText("");
imageLb.setIcon(null);
acessoLabel.setText("");
matriculaTxt.setText("");
observacaoTxt.setText("");
System.err.println("ENTER");
PendenciasTableModel ptm = new PendenciasTableModel();// vazio
pendenciasTabela.setModel(ptm);
matriculaTxt.setEditable(true);
matriculaTxt.requestFocus();
}
}
});
}
What I wanted to do was simple. The user types in the text field their numbers, pressing ENTER: their data are loaded. requestFocus() into the text field and it will not be editable anymore, because when I press Enter again the field will be editable but everything will be deleted, and so on.
First off, you should never use a KeyListener for this sort of thing. Consider instead using either a JFormattedTextField or using a DocumentFilter to prevent non-numeric entry. Next, you should use an ActionLIstener to have the JTextField accept and react to the user's pressing the Enter key.
Edit
You state:
my exact requirements is, when i press ENTER again all data will be cleaned for a new data be inserted.
Why not simply have in your JTextField's ActionLIstener:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText();
// do what you want with text here
// clear the text
textComp.setText("");
}
Again, you should not use a KeyListener for any of this stuff.
Edit 2
If you want a multi-state action listener, one that reacts differently depending on the state of the program, then give it some if blocks to allow it to react to the state of the JTextField. If the field is empty, do one thing, if it has numbers, do another, if it has text, show a warning and clear it:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText().trim(); // trim it to rid it of white space
if (text.isEmpty()) {
// code to show a profile
return; // to exit this method
}
// if we're here, the field is not empty
if (!text.matches("[0-9]+")) {
// show a warning message here
} else {
// numeric only data present
// do action for this state
}
// clear the text
textComp.setText("");
}
The key again is to not use a KeyListener, but rather to "listen" for the enter key press with the ActionListener only, but to react differently depending on the state of the program, here likely being depending on what content is present in the JTextField.
I think that your problem that the KeyListener it'll not trigger, it will not execute the code inside it, because whenever you press ENTER it will trigger the matriculaTxtActionPerformed then declared the KeyLister, so the ENTER will effect it.
Related
I have a JEditorPane with text/html type. When an enter key is pressed with the editor focused, I want to do some checks about the state of the document and then override the enter key default functionality if conditions are met.
I believe this can be done with a KeyListener listening for a key, then consume the event if conditions are met to cancel the key making any change to the input. Testing this idea I'm just trying to consume the key event when any key is pressed. The key listener below is printing output when i press any key, but the characters are still getting inserted into the editor pane.
How can I stop the characters getting inserted altogether?
Thanks for your help.
String content = "";
String type = "text/html";
editor = new JEditorPane(type, content);
editor.setEditorKit(new HTMLEditorKit());
editor.setEditable(true);
editor.setPreferredSize(new Dimension(500, 500));
panel.add(editor);
editor.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e){
System.out.println("huh?");
e.consume();
}
});
EDIT----------
Removed key listener, and added instead
Action enter = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("enter!");
if ( condition == true ){
// default enter key behaviour
}
}
};
editor.getActionMap().put("insert-break", enter);
Ok I got rid of the KeyListener and added this, which prevents the default enter-key functionality which is great. But how would i insert a break (the default enter key behaviour) if my if clause is true?
I can't figure out how to trigger that on the editor programmatically.
You are over thinking it.
We save the Action because we want to invoke the actionPerformed(...) method of the Action.
Assuming the original Action is stored in the variable "original" the code would be:
if (condition == true)
original.actionPerformed( e );
The problem is that when i click on the surname field when the name field is empty both messages appear because the focus is lost even from surname when the message dialog appears. Is there anything i can do to make the program show the name message and the focus to stay on the name field?
I tried the .requestFocus() but it didn't work.
private void NameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (NameField.getText().equals('smth')) {
JOptionPane.showMessageDialog(null, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
private void SurnameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (SurnameField.getText().equals("smth")) {
JOptionPane.showMessageDialog(null, "Please put a surname!","Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
First off, in the NameFieldFocusLost event: if (NameField.getText().equals('smth')) { doesn't fly. The equals() method requires a String: if (NameField.getText().equals("smth")) { or better yet...since you want to ensure a name is actually provided:
if (NameField.getText().trim().equals("")) {
There must be something we're not being shown. I don't understand why both MessageBoxes would be displaying when focus is taken away from the nameFieldFocusLost event. This shouldn't happen unless you have code somewhere moving focus around especially before your form is actually visible. The requestFocus() method should work as well and should be called directly after you display the MessageBox, for example:
private void nameFieldFocusLost(java.awt.event.FocusEvent evt) {
if (nameField.getText().trim().equals("")) {
JOptionPane.showMessageDialog(this, "Please put a name!","Error!", JOptionPane.INFORMATION_MESSAGE);
nameField.setText(""); // Clear the JTextField in case a white-space was placed there.
nameField.requestFocus(); // Force focus back onto the JTextField.
}
}
If you are moving focus to a JTextField before the parent container is visible (Form / JDialog) then you could possibly experience your particular problem.
EDIT:
Ahhh...I see the problem, thank you for the comment. Here are a few ways you can get around this dilemma:
Add a condition within the focusLost event for the next
JTextField to be in focus which will force an exit of that event
should the validation of the previously focused JTextField fail.
In your case you have a First Name text field and a Last Name text
field. In the focusLost event for the Last Name field you would have
the very first line of code being:
if (nameField.getText().trim().equals("")) { return; }
This way the remaining event code doesn't get run in the Surname
Lost Focus event unless validation for Name field is successful. The
entire Surname event code may look like this:
private void surnameFocusLost(java.awt.event.FocusEvent evt) {
if (nameField.getText().trim().equals("")) { return; }
if (surnameField.getText().trim().equals("")) {
JOptionPane.showMessageDialog(this, "Please put a last name!","Error!", JOptionPane.INFORMATION_MESSAGE);
surnameField.setText(""); // Clear the JTextField in case a white-space was placed there.
surnameField.requestFocus(); // Force focus back onto the JTextField.
}
}
An other way would be to utilize the InputVerifier
Class.
There is good example of its use in this SO
post.
Don't use the JTextField's Focus Events at all. If there is a button
that will be selected to further processing with the inputted data
then check the validation for all your JTextFields there (in the button's actionPerformed event) and force a
focus upon the field that fails (nameField.requestFocus();) for proper input.
Here is my application. It's a wallet to update my money when I spend or get profit. Look it up on image hosting here http://tinypic.com/r/687bdk/8
Is there a way to detect that a cursor has been put into one of the JTextFields? If there is, then could I dispatch a method that would delete whatever is in the other JTextField? There should only be one JTextField with input, it is unacceptable to have inputs in both text fields.
You can add a FocusListener to each textfield i.e.
JTextField myTextField = new JTextField();
myTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
//when selected...
}
#Override
public void focusLost(FocusEvent e) {
//when not selected..
}
});
Is there a way to detect that a cursor has been put into one of the JTextfields? If there is, than I could dispatch a method that would delete whatever is in the other JTextField.
As a user I'm not too crazy about that design. I've used accounting type applications before where you have two columns (debit/credit) and a number can only be entered into one.
In those applications the number is not removed on focus, it is removed if a value is entered in the other field. This allows for tabbing between fields on the forum without data disappearing just because focus changes.
To implement this type of functionality you would add a DocumentListener to the Document of the text field. Then whenever text is entered into the Document the listener is invoked and you can clear the text from the other text field.
Check out the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.
It called: CaretListener
jTextArea=new JTextArea();
jTextArea.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e){
//your code
}
}
);
It mainly used when you need to know that your caret position is changed.
I'm working on a JTexfield which sets its own text to the name of the key pressed when it has the focus on the window. I've managed to let it have only a word with the code:
#Override
public void keyReleased(KeyEvent ev) {
if (ev.getKeyCode() != 0) {
keyTrigger = ev.getKeyCode();
txtTrigger.setText(ev.getKeyText(keyTrigger));
}
}
#Override
public void keyTyped(KeyEvent ev) {
txtTrigger.setText("");
}
However it looks horrible when you press special keys like F1--12 or Ctrl because it keeps the last typed non-special key (for example, if you press 'T' and then 'Ctrl', the text in the field keeps being 't' until you release the 'Ctrl' key).
This is the code so far for the JTextField:
txtTrigger = new JTextField();
txtTrigger.setColumns(10);
txtTrigger.addKeyListener(this);
txtTrigger.setBounds(80, 5, 64, 20);
contentPane.add(txtTrigger);
What I want is the field to be empty until you release the key. How can I get the application working this way?
I don't think a editable text field is your best choice here. What I've done in the past is basically faked it.
I've generated a custom component that "looks" like a JTextField and, using my own KeyListener, I've added elements to the view (I did my own "key" renderer, but you could simply have a list of String elements that you can render).
Basically, when keyPressed is triggered, I would add the key code to a list (taking into consideration things like its modifier state). If another key event is triggered with the same key code, then you can ignore it.
When keyReleased is triggered, you can remove that keycode from the active list.
You can add the keylistener to the jframe or many components...
Just make sure that component has the focus.
before I start, I'm a beginner programmer.
How can I enable a text field when a button is clicked.
I have two frames, one that has the JFields and the other for the exception.
When the exception occurs > setEditable(false)
but what statement should I make to enable the JFields once the user click on okay button -that i've made in the exception-?
I've tried to add static boolean to exception frame, and inside the action performed of this class I initialized that boolean to true.
in the other class, I added an if statment, if that boolean is true, then setEditable(true)
-========-
The point of this program, that when the exception occurs the user cannot enter anything in the fields until he closes the exception window.
I wish you'd help me.
With all love, programmers.
The code of action performed for THE EXCEPTION WINDOW FRAME ( having Okay button. )
public void actionPerformed(ActionEvent e){
{
allow=true; //static boolean
Container TheFrame = OKButton.getParent();
do TheFrame = TheFrame.getParent();
while (!(TheFrame instanceof JFrame));
((JFrame) TheFrame).dispose();
}
The code of action performed for THE MAIN PROGRAM (having three fields, an exception will occur once the user enters non digits )
I added some comments to clarify.
public void actionPerformed(ActionEvent event) {
try{
r =Double.parseDouble(RField.getText());
s=Double.parseDouble(SField.getText());
h=Double.parseDouble(HField.getText());
Cone C = new Cone(r,s,h);//class cone
if (event.getSource() instanceof JButton) {
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == VolumeButton) {
Result.append("VOLUME = "+C.volume()+ "\n");
ifV= true;//this's for clearing the fields for new entries.
}
if (clickedButton == AreaButton) {
Result.append("SURFACE AREA = "+C.surfaceArea()+ "\n");
ifA= true;//this's for clearing the fields for new entries.
}
if(ifA&&ifV){ // clearing the fields for new entries.
SField.setText(CLEAR);
HField.setText(CLEAR);
RField.setText(CLEAR);
ifV=false; ifA= false;}
}
SList.addShape(C);
}
catch(NumberFormatException e){
//Object of type "Exception__" already created
Ex.setVisible(true);//class "Exception__" is the one i've made for Exception window
SField.setText(CLEAR);
HField.setText(CLEAR);
RField.setText(CLEAR);
SField.setEditable(false);
HField.setEditable(false);
RField.setEditable(false);
}/*here, if the user clicked on -that okay in Exception window-
and variable allow initialized to "true" those statements should extend. I guess?
- everything worked correctly except for this ?*/
if(Ex.allow){
SField.setEditable(true);
HField.setEditable(true);
RField.setEditable(true); }
}
THANK YOU ALL IT FINALLY WORKED.
I added
Ex.allow(SField,HField,RField);
to the catch.
and added this method in class Exception__:
public void allow(JTextField js,JTextField jh,JTextField jr){
HField =jh;
SField =js;
RField =jr;
}
finally, to the action performed of class Exception__:
SField.setEditable(true);
HField.setEditable(true);
RField.setEditable(true);
WOHOOOO. It feels so awesome lol. Thanks all. should I delete my question or leave it for others who might face the same problem as mine? :P
Your question needs a lot more detail. But if all you want to to show an 'exception window' and allow the user to do anything else only after she dismisses this window, I think all you need is a MessageDialog:
See JOptionPane
If you need more details to be displayed you can create your own modal JDialog.
See How to Make Dialogs
Make the text field hiden by writing:
jTextfield.setVisible(fasle);
in the constructor of your form code. than use the button event " Action -> Action Performed " and write the code:
jTextfield.setVisible(true);
and thus your text field will be visible only after the button will be clicked.