Pass button click event to actionPerformed on key press - java

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
}

Related

java swing manual start an event without user input

I want to activate an event without clicking all the button interface.
ex. when i click button_0, it will print red, and at the same time it will perform action on button_1 and button_2, hence will also print blue and green at the same time.
Those three operation must be separate, solution as merging both action is not applicable on my case, I only made the example as a small guide.
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button_0)
{
System.out.println("red");
}
else if(e.getSource()==button_1)
{
System.out.println("blue");
}
else if(e.getSource()==button_2)
{
System.out.println("green");
}
}
Here's a dirty way to do it:
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button_0)
{
System.out.println("red");
button_1.doClick();
button_2.doClick();
}
else if(e.getSource()==button_1)
{
System.out.println("blue");
}
else if(e.getSource()==button_2)
{
System.out.println("green");
}
}

Button actionlistener calls another action listener in the same class

I have a submit button (and an action listener) which checks if the number inserted into a Futoshiki puzzle is legal (checking a 2D array for duplications etc)
In another method I have the actual grid with an action listener that gets the numbers and inserts them into the 2D array.
JButton acction listener
JButton isRight = new JButton("Check My Answer");
isRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
puzzle.getProblems(),
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
"YOU WIN!",
"YES THATS FINE",
JOptionPane.INFORMATION_MESSAGE);
}
puzzle.printProblems.clear();
}
});
Grid action listener
public void keyReleased(KeyEvent e) {
String getInsertedValue = Emptysquare.getText();
int getInsertedIntValue = Integer.parseInt(getInsertedValue);
setSquareValue(r, c, getInsertedIntValue);
System.out.print(getSquareValue(r, c));
}
Is there a way I can access the keyReleased action listener from the JButton so it basically "submits" the contents of the grid and then checks if its legal?
Sure, just either keep a reference to that action listener and call the keyReleased method with a null value, or refactor out the content of keyReleased to an own method and call this method from both listeners.
Although 2 other methods were given, here is an additional way you could go about it, but I'm not sure which would be best to use.
public class YourClass {
JButton isRight;
public YourClass() {
this.isRight = new JButton();
this.isRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
YourClass.this.isRight.getKeyListeners()[0].keyReleased(null);
//Other action related code
}
});
isRight.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
//Key related code
}
//Other required key listener methods
});
}
}

JFormattedTextfield.selectAll() does not work when formatting the text

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

Get focus back in textField from other frame in java

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.

MouseEvent is not Firing in JList after it's Removed and Added back to a JPanel

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.

Categories