I have two JFrames, when clicked on a textField in Parent form a small form appears with focus on it's textField, on process when this current form disappears, I want to get focus back on the Parent form's textField, that is explained in the images below, how can I do that?
IMAGE
Wha I did is tried to take focus by requestFocus() method to Parent form's textField as below!
CODE FOR SMALL WINDOW
quantityField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER && priceField.getText().length() > 0) {
if (containsOnlyNumbers(priceField.getText())) {
productPrice = Double.parseDouble(priceField.getText());
productQuantity = Double.parseDouble(quantityField.getText());
TaxInfo tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(), m_oTicket.getCustomer());
addTicketLine(new TicketLineInfo(oProduct, productQuantity, productPrice, tax, (java.util.Properties) (oProduct.getProperties().clone())));
status = true;
jProductList.requestFocusInWindow();
frame.dispose();
} else {
JOptionPane.showMessageDialog(null, "Invalid value entered!", "Error", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
TaxInfo tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(), m_oTicket.getCustomer());
addTicketLine(new TicketLineInfo(oProduct, dMul, dPrice, tax, (java.util.Properties) (oProduct.getProperties().clone())));
status = true;
jProductList.requestFocusInWindow();
frame.dispose();
}
}
});
CODE FOR PARENT FORM
jProductList.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (jProductList.getSelectedIndex() < 0) {
//Do nothing
} else {
//Add product into list
m_returnObj = (ProductInfoExt) product.getProductDetail(product.getProductCode(jProductList.getSelectedItem().toString()));
jProductList.setSelectedIndex(-1);
if (addTicketLine(m_returnObj, 1.0, m_returnObj.getPriceSell())) {
System.out.println("Requesting focus");
jProductList.requestFocusInWindow();
}
//jProductList.requestFocus();
}
}
}
});
WHERE jProductList is the Parent form's textField I need to get focus on!
I have two JFrames,
An application should only have a single JFrame. In your case the child window should be a modal JDialog.
when clicked on a textField in Parent form a small form appears
Don't use a KeyListener.
You should add an ActionListener to the text field in the parent form. The ActionListener will be invoked when the Enter key is pressed.
Focus will then automatically go back to the text field when the modal dialog is closed.
In the child form you again should not be using a KeyListener. You can again add an ActionListener to the text field. To handle the Escape key you should be using Key Bindings.
Related
I am making JTextFields which should be populated when click on a button.
Suppose for an example:
txtField1.addFocusListener(new FocusListener() {
JTextField field = txtField1;
#Override
public void focusGained(FocusEvent e) {
btnMain_0.addActionListener(ee -> {
if (field.getText().length() > 4)
return;
else
field.setText((field.getText() + "0"));
});
}
#Override
public void focusLost(FocusEvent e) {
}
});
txtField2.addFocusListener(new FocusListener() {
JTextField field = txtField2;
#Override
public void focusGained(FocusEvent e) {
btnMain_0.addActionListener(ee -> {
if (field.getText().length() > 4)
return;
else
field.setText((field.getText() + "0"));
});
}
#Override
public void focusLost(FocusEvent e) {
}
});
But if I click on txtField1 and press btnMain_0, it enter 0.
Then if I click on txtField2 and press btnMain_0, it enter 00 (it considered pressing btnMain_0 two times).
How I can make it? Is there better solution two run listeners from list of jtextfields?
You can define a custom TextAction and add it to your buttons.
The TextAction allows you to track the last text component that had focus (before you click on the button).
Something like:
class KeyboardAction extends TextAction
{
private String letter;
public KeyboardAction(String letter)
{
super(letter);
this.letter = letter;
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.setCaretPosition( component.getDocument().getLength() );
component.replaceSelection( letter );
}
}
You then use the class like:
jButton1 = new JButton( new KeyboardAction("1") );
jButton2 = new JButton( new KeyboardAction("2") );
or you add the Action to an existing button by using:
button.setAction( new KeyboardAction("1") );
I have a lot of different JFormattedTextFields with action and keylisteners. Every Field has a keylistener, so when I press enter I will focus the next JFormattedTextField. The Problem is, for some JFormattedTextFields my code is formatting the input and then sets the text new and for those selectAll() does not work.
JFormattedTextField a = new JFormattedTextField(someDouble);
JFormattedTextField b = new JFormattedTextField(someDouble2);
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
leasingfaktor1Field.selectAll();
if(...) {
//do something
a.setText(tausenderPunkt(someValue));
}
}
});
a.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
b.requestFocusInWindow();
}
}
});
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
leasingfaktor1Field.selectAll();
if(...) {
//do something
b.setText(tausenderPunkt(someValue));
}
}
});
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
c.requestFocusInWindow();
}
}
});
The function tausenderPunkt():
public String tausenderPunkt(double value) {
String s = String.format("%1$,.2f", value);
return s;
}
So when my cursor is in field a and i press enter the cursor goes to field b but does not select the text or values. When i do not use setText() i do not have the problem. Somebody has a solution?
Edit: For some JFormattedTextFields the solution was to add selectAll() to the keyAdapter, but not for all.
For example:
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
c.requestFocusInWindow();
c.selectAll();
}
}
});
Edit2:
The problem seems to be when i create the JFormattedTextFields.
When i do not create them with a value in the constructor it works.
But i have to do.
Before moving to your next text field you should consider handling all the required conditions for the text field you are currently focused on and this would of course include the formatting of values or text supplied to that field. Once all the desired conditions are met then move on to the next text field.
In reality this can all be accomplished through the keyPressed event for your particular situation. There is no need for the actionPerformed event on any of your text fields, for example:
a.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkConditions(a, b);
}
}
});
b.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkConditions(b, c);
}
}
});
//---------- and so on -------------
Here is a simple method so as to eliminate the need for repetitious code:
private void checkConditions(JFormattedTextField fieldA, JFormattedTextField fieldB) {
// Make sure something is contained within fieldA and
// that it's actually numerical text.
if(!fieldA.getText().isEmpty() &&
fieldA.getText().matches("([-]?)\\d+([,]\\d+)?(([.]\\d+)?)")) {
// Convert the supplied text to Double and
// ensure the desired numerical formating.
String res = (String)tausenderPunkt(Double.parseDouble(fieldA.getText().replace(",","")));
fieldA.setText(res);
// Set Focus to our next text fieldB.
fieldB.requestFocusInWindow();
// Highlight the contents (if any) within the
// next text fieldB.
fieldB.selectAll();
}
// If fieldA is empty or fieldA does not contain
// numerical text then inform User and re-highlight
// the entry in fieldA.
else {
JOptionPane.showMessageDialog (null, "Please Enter Numerical Values Only!",
"Incorrect Entry", JOptionPane.WARNING_MESSAGE);
fieldA.selectAll();
}
}
If you want the contents of your first text field to be highlighted as soon as focus has been established upon it (tabbed to or clicked on) then consider using a FocusGained event for that component or any other component where you desire the same effect.
I Hope this has helped in some way.
EDITED!
So as to handle OP's particular situation.
String str=this.getText();
this.setText(str);
this.selectAll();
You can get the focus owner and remove the focusable feature:
Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
When you get the component, put this sentence after load it:
component.setFocusable(false);
I have a JComboBox that is editable. I need to fire event only following situations
user press enter while typing (this can be achieved adding key event listener) OR
user select item from list
in the following code, event fires while user typing in the editor as well,How can i avoid event firing while user typing?
comboForward.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
new Thread() {
#Override
public void run() {
// code after the event.
}
}.start();
}
}
});
I think this is suitable for you. try it.
JFrame frame = new JFrame("Welcome!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_ENTER) {
if (((JTextComponent) ((JComboBox) ((Component) event
.getSource()).getParent()).getEditor()
.getEditorComponent()).getText().isEmpty())
System.out.println("please dont make me blank");
}
}
});
frame.add(cmb);
frame.setLocationRelativeTo(null);
frame.setSize(300, 50);
frame.setVisible(true);
refer here :https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
I have two JLists, jltCategories and jltSubcategories, belonging to the same JPanel. Double clicking on the jltCategories causes the jltSubcategories to be populated with the corresponding subcategories, and jltSubcategories is removed from the JPanel, added back and revalidated.
Double clicking the jltSubcategories AFTER it has been removed/added back does not fire anything. Yet, If I open the program and double click on the jltSubcategories, it will fire its mouse event: It will fire if it hasn't been removed/added back, but it will not fire if it has been removed/added back. Same for jltCategories: if I cause it to be removed/added, it will stop firing. Why is this so? Thank you!
jltCategories.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
jbtNavigate.doClick();
}
}
});
jltSubcategories.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
jbtLoad.doClick();
}
}
});
jbtNavigate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String catName = jltCategories.getSelectedValue();
try {
jpLists.remove(jltSubcategories);
jltSubcategories = new JList<String>(SQL.populateSubcategories(catName));
jpLists.add(jltSubcategories);
jpLists.revalidate();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
jbtLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Testing Testing 213");
}
});
It is not enough to revalidate() the view; you must also let the model notify the view that new data is available.
DefaultListModel model = (DefaultListModel ) jltSubcategories.getModel();
model.fireContentsChanged(0, model.getSize());
If this is ineffective, please edit your question to include an sscce that exhibits the problem you describe.
Addendum: It's not clear why you use a MouseListener to effect the update; use a ListSelectionListener, shown here.
I'm working on a Java assignment that has to be done using AWT. I want a button to trigger by pushing the enter key while the button is in focus. I figured out how to do this in Swing with the doClick() method, but this doesn't seem to work in AWT. So far I'm trying this:
button.addActionListener(this); // Passes value from a TextBox to actionPerformed()
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER) {
actionPerformed(null);
}
}
});
public void actionPerformed (ActionEvent e) {
try {
if (e.getSource() == button) {
// Stuff I want to happen
} else if (e.getSource() == anotherButton) {
// Other Stuff
} else { //third button
// More stuff
}
} catch (NumberFormatException nfe) {
// Null argument in keyPressed triggers this
// catches empty string exception from TextBox
}
}
As I mentioned with the comments, the null argument will trigger the catch. Does anyone have any idea what that argument might be for the button press or perhaps an altogether easier way to go about this? Thanks.
Edit - clarification: actionPerformed() does one of three things with input from a TextBox depending on which of three buttons is clicked. The try/catch is to catch empty string/format exceptions.
You can always have a method called something like onButtonPress(), which your actionPerformed can call, as well as your keyPressed.
button.addActionListener(this);
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
onButtonPress();
}
}
});
public void actionPerformed (ActionEvent e) {
if (e.getSource() == button){
onButtonPress();
}
}
private void onButtonPress(){
// do something
}