Set keyboard shortcut for a JButton? - java

I have a type game in which you have to type the words that appear as fast as possible before the time limit runs out, but every time you type a word, you must move the mouse and click enter and click back into the user input to type the next word. I was just hoping if there was way to use "keyCode.VK_Enter" to issue an Action Command called by the JButton.
Some snippets of my code:
The Enter button and user input and output:
enter = new JButton("Enter");
enter.setFont(serif); //serif is specified earlier
enter.setActionCommand("Enter");
enter.addActionListener(this);
container.add(enter);
userOutput = new JTextField(50);
userOutput.setFont(serif);
container.add(userOutput);
userOutput.setEditable(false);
userInput = new JTextField(43);
userInput.setFont(serif);
container.add(userInput);
userInput.setEditable(false);
The actionPerformed method getting the enter button's action command:
if(userInput.getText().equals(userOutput.getText())){
userInput.setText("");
score += 100;

Why don't you just add an actionlistener to the JTextField (which would be triggered when the user hits enter).
userInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do something
}
});

Related

Issue with numbers not appearing in box when respective button is pressed

I'm making a simple calculator in GUI and I have all the code typed and ready, but I'm having trouble with making it so that when the user presses a number button, the respective number appears in the text box above. Do I need to use a radio button? Thanks in advance
I've tried action listeners but they didn't work (or I'm probably using them incorrectly). I've put the code for the 1 button.
JButton num1 = new JButton("1");
num1 = b1;
num1.setSize(50,50);
num1.setLocation(20,200);
num1.setBackground(Color.WHITE);
num1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Just append the number to the JTextField(using setText(String) and getText()) in the actionPerformed function.

How can my program randomly press a button?

I'm trying to make a game where the button would light up and the user would have to press the button in a given time.
Currently, my program has 12 buttons that do something. I'm trying to make it so that these buttons are randomly called by the program. So far, I just have these for 12 buttons that just change the text when pressed by the user.
Now I need a way of making it so that they are randomly pressed the program itself and not the user. Any idea's on how this is done in java?
// **** Panels for buttons ****
JPanel panelButtons = new JPanel(); // making the panel for the buttons
panelButtons.setLayout(new GridLayout(3, 4)); // setting the layout of the buttons to 3x4 as shown above
b1 = new JButton(" ⃝"); // creating button and setting its default text
b1.setFont(fontText); // setting the font
b1.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "1" ); // sends the name of the user that pressed the button and which button
String field1 = b1.getText(); // gets the text from the button and stores it in a String
if(field1 == " ⃝"){ // checks if the string is equal to an empty circle
b1.setText("⬤"); // if true then change to a full circle
}
else if (field1 == "⬤"){ // opposite of the above if statement
b1.setText(" ⃝");
}
}
});
panelButtons.add(b1); // adding the button to the panel
b2 = new JButton(" ⃝"); // creating button and setting its default text
b2.setFont(fontText); // setting the font
b2.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "2" ); // sends the name of the user that pressed the button and which button
String field2 = b2.getText(); // gets the text from the button and stores it in a String
if(field2 == " ⃝"){ // checks if the string is equal to an empty circle
b2.setText("⬤"); // if true then change to a full circle
}
else if (field2 == "⬤"){ // opposite of the above if statement
b2.setText(" ⃝");
}
}
});
panelButtons.add(b2); // adding the button to the panel
You can create a list that holds your button. Use the random number generator to create a random number within the length of the list. Use that (random) index to modify the corresponding button.
Put your twelve buttons in an ordered collection.
Put your twelve corresponding actions in another ordered collection in form of a Consumer<JButton>'(useCallable`(and ignore the return) or just create something like that if you are not using java 8).
Perform a mapping from the Button collection to the action collection.
Create a class implementing ActionListener like this:
private static class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
button2action.get((JButton)e.getSource()).accept(a);
}
}
pick up a random element from the value set of the map if you want to get random button pressed.
int randomIndex = new random().nextInt(button2action.entrySet().size());
Iterator<Entry<JButton, Consumer<JButton>>> iter = button2action.entrySet().iterator();
for (int i = 0; i < randomIndex; i++){
Entry<JButton, Consumer<JButton>> entry = iter.next();
}
entry.getValue().accept(entry.getKey());
add new button action pairs to the map if you want to add new buttons.

Taking a Textfield input converting to an int and then limiting the value

So im trying to take a Textfield input parsing to an int and then having on pressing enter. If the value is between say 1 and 50 you get an error if not it goes to the rest of my program. Im currently just testing to see if i can get the Action event to work.
This is what I have currently.
I get bad operand <= and >. I am not looking for anyone to just solve this but if anyone has any links or suggestions on what I am doing wrong that would be most appreciated.
public void init()
{
setLayout( new FlowLayout());
label1= new JLabel( "Please enter number of rows" );
tf1= new JTextField(5);
String text = tf1.getText();
int first=Integer.parseInt(text);
add (label1);
add (tf1);
tf1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//System.out.println("Enter pressed");
if (e.getSource()<=20){
System.out.println("Correct");
}
else if (e.getSource()>20){
System.out.println("Try again");
}
}
});
}
You expect e.getSource() to be the number entered, but what you get is the TextField which caused the event to happen. You can't compare a TextField to a number using < or such.
Since you register the ActionListener directly on the TextField, you don't have to check the source of the event. You know it will be the TextField.
What you want to do is :
In the case of an event (the actionPerformed() only gets called when an action happened in the TextField), if the key pressed was Enter, get the number from the TextField and check its value.

Problems with KeyEvent

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.

Java set buttons names automatically

I'm new in Java swing, and I have a problem. I made for-loop for creating buttons and now I want automatically give them names or some kind of marks for future recognition (I will need name of clicked button to make it a variable).
How can I give them names in my loop? Thank you.
Here is code of my for-loop:
for (int aa=1; aa<65; aa++)
{
JButton button = new SquareButton("");
gui.add(button);
button.addActionListener((ActionListener) button);
}
I will need name of clicked button to make it a variable).
You don't need a variable to work with the clicked button. Instead you get a reference to the button that was clicked from the ActionListener code:
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
// do processing on the clicked button.
}

Categories

Resources