Textbox keyListener in Java - java

so I have this part of my code (I cannot post everything because it's just too long and so far this is the only problem with it). Our professor assigned us to make our own Assembler just like MARIE and we are having a trouble with these lines of code:
else if(get.charAt(0)=='B')//input
{
inputfield.setEditable(true);
//INSERT LISTENER HERE!
AC.setText(inputfield.getText());
System.out.println(""+col);
//insert action here - HALP
}
The entire thing gets a value from a table sort of like an Instruction in Hex and if the Intruction starts with B like B000 then it will toggle the input textbox which is named inputfield. It works fine but we need to add a key listener in the part where it says //INSERT LISTENER HERE! for when the user will press enter the AC.setText(inputfield.getText()); will be executed. How should we do it? I mean we tried actionListener but it sort of stops the loop unless another button is clicked. We need another way that when the user presses enter it automatically resumes the execution.
Thank you.

Add action listener to textfield. ActionEvent will occur when you press Enter while editing in textfield.
JTextField field = new JTextField();
field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// action to perform when one hits "Enter"
}
});

Related

Want to halt code until user uses a button

So I am trying to run a code, open a GUI window, choose between two buttons, which set a value and then with this value continue the rest of the code.
I have seen similar questions or Tutorials, but I do not find the suitable solution for my problem.
As I have already seen, JFrame, ActionListener and ActionEvent have to be used in order to make a GUI with a button.
An Object which extends JFrame and implements ActionListener is writen in the main method.
The Problem is, that the code writen in the main method opens the GUI window and continues to run. I just want that the code waits till the user clicks a button and then continue.
A sub-solution is, to write the code that I want in the actionPerformed method but:
The GUI window remains open, after the selection of a button
It makes no sense to me to write the rest of the code in the actionPerformed method.
Or to write a while loop until a button is clicked. A more sensible solution has to exist that I am not aware of or I do not understand the way this should work.
Here is a part of the code.
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == testStringA) {
setVariableTo = "testString_a";
try {
runMethodWithNewVariable(setVariableTo);
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
} else {
setVariableTo = "project";
try {
runMethodWithNewVariable(setVariableTo);
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
}
Instead of a JFrame, why don't you use a JOptionPane (showOptionDialog) with two buttons, "string A" and "project" instead of "Yes" and "No", for example?
JOptionPanes like "show Option Dialog" are intrinsically blocking. If you put one in your main() method, execution will "wait" for the user to select something in the dialog and the dialog will return an indicator to what was selected before execution in main() continues.
At the begining of your program, show a modal JDialog to the user! You can do this using JOptionPane.show() methods, like this:
String[] buttonTexts = {"first","second"}; //create the button texts here
//display a modal dialog with your buttons (stops program until user selects a button)
int userDecision = JOptionPane.showOptionDialog(null,"title","Select a button!",JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE,null,buttonTexts,buttonTexts[0]);
//check what button the user selected: stored in the userDecision
// if its the first (left to right) its 0, if its the second then the value is 1 and so on
if(userDecision == 0){
//first button was clicked, do something
} else if(userDecision == 1) {
//second button was clicked, do something
} else {
//user canceled the dialog
}
//display your main JFrame now, according to user input!
You basically have two threads running - the main thread and the GUI thread. You don't explicitly create the GUI thread but it is there.
You can use a number of techniques to synchronise these two threads. The most basic is the good old synchronized, wait and notify. Something a Semaphore can also be used. In the main thread you would create the GUI and wait until a condition is met. In the GUI thread (i.e. actionPerformed) you would notify.

how to start key listener at the start of program in java

So I have three labels and I added a mouse clicked listener on them. If I clicked the label, the value inside the label will change. Now, I want to add a key press listener. When I press letter a for example, I want my label1 to change also its value. I already made a keyeventlistener for that but it doesn't do what I want.
private void secondKeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode()==KeyEvent.VK_A){
int number = Integer.parseInt(second.getText());
number = number + 1;
String number1 = String.valueOf(number);
first.setText(number1);
}
}
My program has 3 buttons so when I start my program, the first button is highlighted so I guess, that's the place where I should do an event listener? Is there anyway that I can start adding key event listener on the very start of my program?

Java Swing JTextField setInputVerifier keep focus on TextField

I have a public class JdbDateTextField extends JTextField and in the constructor I add this.setInputVerifier(new ValidDateOrEmptyVerifier());.
I use class ValidDateOrEmptyVerifier extends InputVerifier to verify the format of the input.
If the input is in the wrong format and the user looses the focus of the JdbDateTextField, I return false in the ValidDateOrEmptyVerifier and the focus is gained again to the JdbDateTextField again.
This works if the user switches from the JdbDateTextField to another textField or presses a Button. If pressing a button and the format of the input in the is wrong then no action for the button is performed and the focus is still at the JdbDateTextField.
This is exactly what I want. The user can not leave the JdbDateTextField until he enters a valid string.
The problem is that the JdbDateTextField is in a JPanel which is in a JTabbedPane so I have a GUI with several tabs.
If I have the JdbDateTextField selected, enter a invalid input and then directly click on another tab it still switches the tab. So I was able to provide a wrong input.
My Question is:
Is there a way to perform an Input Verification which does not allow to execute any other event before it is true
The best solution I can think of is to assign the JTabbedPane a custom selection model which refuses to allow changing tabs unless the current InputVerifier succeeds:
int index = tabbedPane.getSelectedIndex();
tabbedPane.setModel(new DefaultSingleSelectionModel() {
#Override
public void setSelectedIndex(int index) {
Component focusOwner =
FocusManager.getCurrentManager().getFocusOwner();
if (focusOwner instanceof JComponent) {
JComponent c = (JComponent) focusOwner;
InputVerifier verifier = c.getInputVerifier();
if (verifier != null && !verifier.shouldYieldFocus(c)) {
return;
}
}
super.setSelectedIndex(index);
}
});
tabbedPane.setSelectedIndex(index);
I hope that I can do this as an answer:
The solution above works for the JTabbedPane
But I can still select other GUI elements.
My Application is build like this:
For every Person ID I show other Birthdate values in the JTabbedPane
and I can still switch to another Person ID if the ValidDateOrEmptyVerifier returns false.
So is there a way to disallow all events in the Main Frame until the ValidDateOrEmptyVerifier returns true.
So Basically what I want is that the user can only exit the "Birthdate" JdbDateTextField if he enters a valid Date or the field is empty.

Console Interface Navigation Button Listener - java

I'm writting a console interface for a small program I'm doing. I display something like this on the console:
Please select:
1)Add user
2)Delete user
3)Edit user
The method it self should listen for a button push, and if that button push is one of the digits 1,2 or 3 it should call some other method and clear all the text from the console. Something like this:
display the above info
if(button is not pushed)
do nothing
else if ( button == 1)
call method addUser and clear everything on the console, so that addUser
can display it's info
I know the question does not contain any code, but I have no idea how to do this. I know there should be some kind of button listener, but have no idea what to use and how. Any help is welcomed :)
You'll have to add an event listener to the button(s), and when that specific button is clicked, you call the required methods.
If you're not familiar with event listeners, I strongly suggest you check out https://docs.oracle.com/javase/tutorial/uiswing/events/intro.html and related pages on the official documentation portal.
Hope this helps.
This code can guide you to your solution. Use BufferedReader to read from console and check codes for buttons which was pressed, and depending on them, call the appropiate methods.
public static void main (String[] args) throws IOException {
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hit 1, 2 or 3");
int buttonCode = bufferRead.read();
System.out.println("Code of button hit is: "+buttonCode);
//Button Codes for 1, 2 and 3 keys are 49, 50 and 51 respectively
if (buttonCode==49) {
//DO insert user
} else if(buttonCode==50) {
//Do delete
} else if (buttonCode==51) {
//Do Edit
} else {
System.out.println("Wrong button pressed");
}
}

Hold down a key while clicking on a JTextField in Java, how to get the key?

I have a JTextField represents a day in a week, such as "Friday", when I click on it, I want to have a choice such as "1st of month, 3rd of month or last of month", so I came up with two options :
<1> Hold down a number or letter, let's say "2" or "L", then click on "Friday" means 2nd (or last) Friday of the month, in this case, how to get the number while mouse clicks on the JTextField ?
<2> Right mouse click on the "Friday" JTextField, drop down a menu, with either buttons or checkboxes that let me choose, then close the menu and get the value.
My code look like this so far :
private final JTextField[] dayHeadings=new JTextField[]{new JTextField("Su"),
new JTextField("Mo"),
new JTextField("Tu"),
new JTextField("We"),
new JTextField("Th"),
new JTextField("Fr"),
new JTextField("Sa")};
......
for (int ii=0; ii < dayHeadings.length; ii++)
{
dayHeadings[ii].setEditable(false);
dayHeadings[ii].setFocusable(false);
dayHeadings[ii].addMouseListener(new MouseAdapter() { public void mouseClicked(final MouseEvent evt) { onHeadingClicked(evt); } });
add(dayHeadings[ii],new AbsoluteConstraints(x,38,X_Cell_Size+1,Y_Cell_Size+1));
}
......
void onHeadingClicked(final java.awt.event.MouseEvent evt)
{
final javax.swing.JTextField fld=(javax.swing.JTextField) evt.getSource();
...
}
How to do either of the above, are they doable in Java ?
getModifiers is actually that what I needed. a sample for the modifiers can be found
here
Option 1:
There is no way to do this in one step. You would need to add a KeyListner to track whenever a key is pressed and then save the character value. Then you would need to add a MouseListener to listener for mousePressed events. When the mousePressed event fires you would need to to check which character is saved and then do your processing. Therefore your listener would to implement both the KeyListener and MouseListener interfaces.
Option 2:
You need to add a mouse listener and listen for a right mouse click, then display a popup menu.
I think option 2 is more intuitive and more easily done. Its always easier to work with one hand then be forced to use two hands.
Another, lazier way to do it would be using getModifiers() on the mouseclick event. It shows which modifier keys (ctrl, alt, shift, etc), if any, were pressed during the mouse click. Using these buttons isn't as intuitive as a drop down menu or numbers in my opinion, but could work.
Read more here

Categories