one jbutton doing different actions when clicked again - java

I need the same JButton to perform a different actions once it's clicked again. Like the first time I click the button, a text will appear in the first row of my JTextField, then the second time I click it, a text will appear in the second row if text field. How should I do it?
Here is my code BTW:
private void addActionPerformed(java.awt.event.ActionEvent evt) {
String items1 =(String)list.getSelectedItem();
String qty1 = qty.getText();
String price1 = price.getText();
int qty2 = Integer.parseInt(qty1);
int price2 = Integer.parseInt(price1);
if(evt.getSource() == add){
order1.setText(Integer.toString(qty2));
order2.setText(Integer.toString(price2));
order3.setText(items1);
}
I literally have no idea what to do next.
Here is the pic for the design GUI: http://prntscr.com/pfh96z

Take a Boolean isClickedOnce and change its state upon clicking on your button
private Boolean isClickedOnce = false;
//..
private void addActionPerformed(java.awt.event.ActionEvent evt) {
if(!isClickedOnce) {
//first click
//..
} else {
//second click
//..
}
isClickedOnce = !isClickedOnce;
}
Note: it'll consider every odd number click as first click and every even number of click as second click. it will toggle through your first and second row.
If your case is different lets say you have n number of rows, above procedure won't work and you might wanna do something similar with a list.

Related

How do I implement something after a series of button clicks in a certain order and within a certain time period in Android studio if I had 2 buttons

If I had 2 buttons in the android studio and if I wanted to implement something when the 2 buttons are pressed in a certain order and within a certain time period, how would the code be like?
Supposing 2 buttons, button1 and button2 and if pressed in the order button1, button2, button2, button1 implements some activty.
button1.onClick ----(within 1 second)---> button2.onClick ----(within 1 second)---> button2.onClick ----(within 1 second)---> button1.onClick -----> Then do some activity.
I hope this explains what I'm trying to achieve.
Any help is much appreciated. :)
UPDATE
This is what I have so far but I am nowhere close to even sure if this is the right way to go about this
I put an on click listener for both
buttonOne.setOnClickListener(this);
buttonTwo.setOnClickListener(this);
Then
public void onClick(View view) {
if(view == buttonOne) {
//a timer for 1 second {
if(view == buttonTwo) {
//a timer for 1 second {
if(view == buttonTwo) {
//a timer for 1 second {
if(view == buttonOne) {
startActivity(new Intent(this, Some.class));
}
}
}
}
}
}
}
}
The solution works by using handlers and delaying doing something for some time for this case 1 second. Because all the buttons have integer ids then the solution will work to prepare for you an integer array for ids in the right order you can later on loop in an array checking the ids in it comparing it with id of your buttons. Initially all button ids are zero (0), And if they user clicks the button he will be adding the right integer id if he doesnt click any other button in a period of 1 second. All ids in the array will be zero (0) again, except only if the last click is the 4th click and after that you will have to handle your logic by checking the array yourself.
Lets start by declaring the variables we shall use (Remember to read comments):
private Handler handler; //handler to delay all work in 1 second
private Runnable runnable; //runnable this will be doing the job in another thread
private int[] buttonIDs = {0, 0, 0, 0}; //all button ids are zero initially
private int pressNumber=-1; //The user has not clicked anything
These are two methods you will have to add in your class.
The first method:
private void startCounter() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
if(buttonIDs[3]==0){ // if the last id is still zero lets clear everything and start afresh
clearEverything();
}
}
}
handler.postDelayed(runnable,1000); // we tell it dont execute the code in run until a 1000 milliseconds which is 1 second
}
And the second method is:
private void clearEverything(){
// clear everything will really start everything afresh always call this method first if you want to repeat the game start afresh
pressNumber=-1;
for(int i=0;i < 4;i++) {
buttonIDs[i] = 0;
}
}
The code inside onClick finally is simply this:
if(pressNumber < 3){
pressNumber++; //increment the pressing to another value
buttonIDs[pressNumber] = view.getId(); //use that value as index to button id
if(runnable != null){
handler.removeCallbacks(runnable); // if there was any handler still running cancel it first because we have clicked some button
}
startCounter(); //after click always start counter and remember if the counter finishes it will reset everything
} else{
//Do something here the user has clicked all the buttons 4 times without delaying 1 second each!. The order of button clicks is the integer array buttonIDs and you can clearEverything(); to start again!
}

EventListener Performed by case

I would like to know the best way to approach what I am trying to achieve, I can't figure out the logical path I should take.
I have a JTextField and a JTextButton, when input is added to the JTextField and either enter or the button is pressed, it will display on the JTextArea. Now, what I want is to choose when and what the JTextArea and Button do.
For example I want default Enter & Button to display next append text in my code. Then when a case is presented I want the JTextField to only accept either int or string and then once completed, I want it to go back to default.
I don't know if what I am trying to do is logical or best practice...
The idea behind this is, I have a story text based gui game. I want it to display text to the JTextArea and when Enter or button is pressed to display the next line of text and when in the story it requires user input, the JTextArea will look for that input.
So far I have an EventListener and ActionListener which submits what I type from JTextField to JTextArea, but that is about it.
Thanks for your assistance! I have solved my issue, not sure if this is the "Best Solution". I combined your solution with a bit of tweaking.
In this instance, buttonState is an int which can be changed throughout my code by calling a constructor "setButtonState". I could have made buttonState a static to make things easier, but thought I could keep things clean.
enterButton.addActionListener(new ActionListener()
{ //This is used so when the enter screen button is pressed, it will submit text from text field to text area.
public void actionPerformed(ActionEvent e) {
String text = inputTextField.getText();
InputTextFieldEvent event = new InputTextFieldEvent(this, text);
if (buttonState == 0) //Displays all text in JTextField to JTextArea, mostly for testing purposes.
{
if (textInputListener != null) {
textInputListener.setInputListenerOccurred(event);
}
}
if (buttonState == 1) //Only accepts string for answer
{
if (inputTextField.getText().matches("[a-zA-Z]+"))
{
textInputListener.setInputListenerOccurred(event);
}
else
{
getAppendMainTextArea("You have entered an invalid input, only letters are allowed.");
}
}
if (buttonState == 2) //Only accepts int for answer
{
if (inputTextField.getText().matches("[0-9]+"))
{
textInputListener.setInputListenerOccurred(event);
}
else
{
getAppendMainTextArea("You have entered an invalid input, only numbers are allowed.");
}
}
}
});

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?

JTextField - Moving cursor using a button

I'm really struggling to find the functionality (if it even exists),
to move a JTextFields cursor by clicking a Button, instead of using the mouse.
For instance, I have my text field with a string added.
By clicking a back button, the cursor will move back through the string, 1 position at a time or forward depending on which button is pressed.
I can do it with the mouse, just click and type, but I actually need to have it button based so that the user can choose to use the keypad to enter a name or just click into the JTextArea and type away.
Is it possible? What methods should I look for if so.
Thank you.
These are sample buttons that are doing what you're asking for:
btnMoveLeft = new JButton("-");
btnMoveLeft.setFocusable(false);
btnMoveLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtAbc.setCaretPosition(txtAbc.getCaretPosition() - 1); // move the carot one position to the left
}
});
// omitted jpanel stuff
btnmoveRight = new JButton("+");
btnmoveRight.setFocusable(false);
btnmoveRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtAbc.setCaretPosition(txtAbc.getCaretPosition() + 1); // move the carot one position to the right
}
});
// omitted jpanel stuff
They are moving the carot in the textfield txtAbc with 1 position per click. Notice, that you need to disable the focusable flag for both buttons, or the focus of your textfield will be gone if you click one of these buttons and you can't see the carot anymore.
To avoid exceptions if you're trying to move the carot out of the textfield boundaries (-1 or larger than the text length), you should check the new values (for example in dedicated methods):
private void moveLeft(int amount) {
int newPosition = txtAbc.getCaretPosition() - amount;
txtAbc.setCaretPosition(newPosition < 0 ? 0 : newPosition);
}
private void moveRight(int amount) {
int newPosition = txtAbc.getCaretPosition() + amount;
txtAbc.setCaretPosition(newPosition > txtAbc.getText().length() ? txtAbc.getText().length() : newPosition);
}

Issues with JtextArea. JAVA

I have a GUI setup with with buttons on them and a JTextArea.
I also have an array of Strings with say size of 3.
What I want to do is use an action listener in a way that when the button called "next" is pressed, the JTextArea will then show the next cell in the array. The only problem is it displays the array at the same time. I need it to display the next cell when the button is hit
Can anyone help me with the code? Please and thank you.
final ActionListener m2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
arr = new String[3];
arr[0]= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
arr[1]= "sssssssssssssssssssssss";
arr[2]= "xxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i<arr.length; i++){
text.append(arr[i]);
}
}
};
next.addActionListener(m2);
So the basic concept is. You need a index value to maintain the current index of the array that is being displayed.
From there, each time the user clicks next, you would increment the index and display the next value in the String
public void actionPerformed(ActionEvent e) {
currentIndex++;
// You need to decide what to do when we reach the end of the array...
String value = myStrings[currentIndex];
textArea.setText(value);
}
To create the button, use the JButton class. To respond to events, use the JButton#addActionListener() method. If you are having trouble, post what you have tried. Good luck!

Categories