So I understand how to make it so when a user presses a button, the count goes up, but how would I make it so it displays the amount of times the button has been pressed in a different way. For example, if the user pressed the button 3 times, it would say 123, instead of 3.
This is my current method with does it a conventional way,
public void actionPerformed(ActionEvent event) {
count++;
label.setText("Pushes: " + count);
}
So I'm thinking maybe I can make it so it loops through each posted value and displays that?
Initialise countStr globally, than on the button click append the count with StringBuilder like:
StringBuilder countStr= new StringBuilder();
public void actionPerformed(ActionEvent event) {
count++
countStr.append(count);
label.setText("Pushes: " +countStr);
}
Related
I am doing a questionnaire with questions and written answers.
I need that when adding the answer, press the main button, tell me if it is correct or not and show me the other question of the array, until the array is finished. Here I upload the whole code.
mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i=0;i<question;i++) {
if(answer.getText()==(option[i])) {
message.setText("is correct");
corrects++;
}
else {
message.setText("incorrect");
}
};
You have the right idea, but you need to process the questions one at a time, not all at once inside the ActionListener.
One way to approach this is to keep track of the question outside of the action listener, in this example we use int questionCounter = 0; to keep track of the current question, then we can remove the for loop and process the questions one at a time. Here is a simple example of how it could work using your code, note how we reset the fields and add the next question every time the previous question is answered.
//Use a variable outside of the action listener to keep track of the current question:
int questionCounter = 0;
//Show first question in the text area:
area.setText(question[questionCounter]);
mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(answer.getText().equals(option[questionCounter])) {
message.setText("The previous answer was correct");
corrects++;
//Update the total each time you get one correct
correct_answers.setText("correct answers: "+corrects);
}
else {
message.setText("The previous answer was incorrect");
}
//Increment for the next question
questionCounter++;
//Check if there is another question, then show it
if (questionCounter < question.length){
answer.setText("");
area.setText(question[questionCounter]);
}
//Show the overall results if there are no more answers to check
else{
area.setText("Quiz complete, you got " + corrects + " out of " + question.length + " correct.");
}
};
I'm trying to code a trivia based game with ActionEvent based buttons. I organized each specific event that is connected to JButton instances in a if-else structure and inside each of these structures, a method would be called. One of these methods would increment a variable that holds the number of the answers that are correct (cor) and wrong (inc):
public void compare(String sel , String ans)
{
//if correct
if(sel.compareToIgnoreCase(ans) == 0)
{
q.setText("Correct! 10 points added!");
score += 10;
cor++;
}
//if incorrect
else
{
q.setText("Incorrect! The correct answer was: " + ans);
inc++;
}
}
This set of code would be run from this:
public void actionPerformed(ActionEvent event)
{
if(e.equals("GUESS"))
{
userGuess = entry.getText();
answer = ans.get(currentQuestionIndex);
base.remove(entry);
base.remove(submit);
submit.setText("OK");
submit.setActionCommand("OK");
submit.addActionListener(this);
base.add(submit);
compare(userGuess, answer);
}
...
}
However, whenever the compare method is called, the inc and cor value seems to increment by an ambiguous value. For example, if I were to answer one question right, the new value for cor would be 2 instead of 1. When I answer another right, cor would be 5 instead of two. I tried using tracers in my code but so far, I appears that the program detects the actionEvent that runs compare() is being pressed multiple times, and as a result, it runs said code multiple times. How can I fix my code so that these variables can be incremented correctly by 1.
submit.addActionListener(this);
Don't add the ActionListener in the actionPerformed() method.
Each time the actionPerformed is invoked you add another listener, so when you click on the "Submit" button you have code that is executed multiple times.
I am making a simple calculator using a JFrame and JButtons. Before I made each button, 0 thru 9, with their own action listeners, now I have realized that this is super inefficient and I should use a loop to make each button and assign the ActionListeners. So the only thing that needs to happen in each ActionListener is to add whatever number the button is to a JTextField, called nums. Here is what I have now.
for(int i = 0; i <=9; i++) {
count = i;
btns.get(i).addActionListener(new ActionListener(){ //makes action listeners for each button
public void actionPerformed(ActionEvent e){
nums.setText(nums.getText()+ count);//IMPORTANT CODE
}
});
}
So as you can see I used a terribly named variable named count. count is set to i in each iteration before the important code is used. I have to do this because an AL is it's own class and cannot access i. However count is public and static, so the ALs can use count.
My problem is that all the buttons print 9. This logically makes sense because what is happening is that the ALs in each button use the count variable, when the loop is done, count will be 9, which means each AL will essentially contain nums.setText(nums.getText()+ 9);. Instead, I need button 1 to be nums.setText(nums.getText()+ 1); 2 to be 2, ETC.
I have tried to call the text of each button, however, because you need to use an index in the ArrayList get method, you need a variable, if you use count, the same problem occurs; after the for loops has terminated, count is 9, so all the buttons print the text of the 9 button.
Any and all help is appreciated, Thanks in advance,
-Max
P.S. Just in case you don't understand why I'm getting the text and then adding count, it is because in order to type the number 12. you need to type 1 and then concatenate the 2 to the one to et 12. getText gets the 1, and adding count concatenates the 2 to make 12.
In general you will want to avoid using static fields as you loose all benefits of object-oriented programming by this. There are specific places for use of static fields, but this is not one of them. In your situation you can't use the index of the loop, i, directly since it is not a final local variable, and non-final local variables cannot be used within anonymous inner classes. So a simple solution exists:
Make count a final local variable and you should be able to use it within your anonymous inner class:
for(int i = 0; i <= 9; i++) {
final int finalCount = i;
btns.get(i).addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
nums.setText(nums.getText() + finalCount);
}
});
}
Assuming the text for each button is simply the digit you wish to append, there is another way that lets you share the same ActionListener instance for every number button.
private ActionListener numberBtnListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
JButton b = (JButton) e.getSource();
nums.setText(nums.getText() + b.getText());
}
}
Then just use the same listener instance for each button:
for(JButton b : btns) {
b.addActionListener(numberBtnListener);
}
If your button text is different for some reason, you can still use the same technique by using a client property on each button to hold the value that you wish to append. E.g.:
b.putClientProperty("digit", i);
then use
nums.setText(nums.getText() + b.getClientProperty("digit"));
I am creating a program that takes an input file, parses that information and builds a GUI calculator from that information. Currently the program works well except for when I implement an ActionListener on buttons that should set a text field to the value of the buttons getText() method.
I have tried a few different loop constructions using for and while, but all of them I have implemented have not found the where i or a counter is equal to the parsed int from numPad.getText() or returned 0 for all of the buttons.
The problem I am having while testing is that the variable i never matches numPoint. Logically my approach is to decrement i so that the loop will continue to look for matches, but never does this. The test output statements infinite loop "-1" for i and "7" for numPoint. As a note, the numPad array is not in order but instead the elements are as follows {7, 8, 9, 4, 5, 6, 1, 2, 3, 0}.
I realize that this loop may not be logically correct, but I am having a hard time finding a solution that works. I want to avoid hard coding if statements (such as i == Integer(parseInt.numPad[0].getText()) which would work.
This is the loop that creates the new buttons and adds them to an Array, sets the text based on a list created from the values of the input file and adds an ActionListener.
for (int i = 0; i < run.buttons.size(); i++) {
numPad[i] = new JButton();
numPad[i].setText(run.buttons.get(i));
numPad[i].addActionListener(new ButtonActionListener());
panel1.add(numPad[i]);
}
This is the most recent attempt at creating a loop that should make the assignment.
public static class ButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int i;
int numPoint;
for (i = 0; i < numPad.length; i++) {
numPoint = Integer.parseInt(numPad[i].getText());
if (i == numPoint) {
//Match, assign
System.out.println("works");
break;
} else {
//Decrement and continue
i--;
System.out.println("test statement" + i + " " + numPoint);
continue;
}
}
}
}
There are several ways you might do this, but let's start with the basics
for (int i = 0; i < run.buttons.size(); i++) {
numPad[i] = new JButton();
numPad[i].setText(run.buttons.get(i));
// You don't "have" to do this, as the action command defaults
// to the text of the button, but this is away to provide some
// kind of identifier to the action which might be
// different from the text
numPad[i].setActionCommand(run.buttons.get(i))
numPad[i].addActionListener(new ButtonActionListener());
panel1.add(numPad[i]);
}
Then in your ActionListener...
public static class ButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
int numPoint = Integer.parseInt(command);
// Perform what ever action you need
}
I am trying to make it so that instead of hitting the enter key in my java program to make the enter action occur, I can instead hit the enter key while a custom method is running. At this point, I have looked into Hashmaps but am pretty confused if this going to do what I want. Any help would be greatly appreciated. It seems like this should be an easy thing to do, but for some reason I am just not getting a solution to it.
So, I am thinking my code will be something like this. Essentially, I am making a game of Hot Potato and I need to have the players take turn entering a character (e, d, and c for team 1 and o, k, and n for team 2). This will be involving a GUI interface as well. A have a while loop that will end once a timer reaches zero. What I would like is for the players to be able to put in a letter into a JTextField in the GUI and then simply press spacebar (as they will be sharing a keyboard). Once they enter the right letter (I made it randomized), they can hit spacebar and they will have "tossed the potato" to the other player.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
I am working all of this out of the actionPerformed(ActionEvent ev) method. The fuller code looks like this. The if statement is commented out because I would like the game to start when the main button is pressed, but right now I get a ton of compilation errors when I uncomment the JButton and have it working with the String text that is the dialogue from the text you enter into a JTextField.
public void actionPerformed(ActionEvent ev) {
Object eventSource = ev.getSource();
String text = entryText.getText(); // text entered into JText
//JButton eventButton = (JButton) eventSource;
System.out.println(text);
//if (eventButton.equals(main))
{
int totalTime = 1000*(HotPotato.randNum());
long startTime = System.currentTimeMillis();
System.out.println(totalTime/1000);
Boolean p1Start = false;
String input = "";
while (System.currentTimeMillis() - startTime <= totalTime)
{
p1Start = !p1Start;
char a = HotPotato.randLetterBoth(p1Start);
String aString = String.valueOf(a);
while (!input.equals(aString))
{
System.out.print(aString); // temporary, shows test letter
input = theKeyboard.next();
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
KeyEvent.VK_ENTER;
}
}
}
}
if (p1Start)
{
System.out.print("Team 2 Wins!");
}
else
{
System.out.print("Team 1 Wins!");
}
setLabels();
myPicture.makeHotPotatoOn(myHotPotato.state());
myPicture.repaint();
}
}