Clear button only makes counter JLabel blank but does not reset it. - java

I have made this application:
For example when I click on the clear button when the counter JLabel (pointsAvailable) is 19 then the counter JLabel goes blank as expected, however when I start adding points again it starts from 19 not 40 as set on the start. I would like to make it to reset back to 40 instead of just making it blank
Code for the clear button
private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {
speedPoints.setText("");
attackPoints.setText("");
defencePoints.setText("");
powerPoints.setText("");
agilityPoints.setText("");
focusPoints.setText("");
availablePoints.setText("");
}
Code for Jlabel counter
public class addingPointsUI extends javax.swing.JFrame {
int pointsAvailable=40;
int speed=0;
int power=0;
int focus=0;
int agility=0;
int defence=0;
int attack=0;
Code for buttons +/-: to allow me to add or decrease value "example power - button"
private void powerMinusActionPerformed(java.awt.event.ActionEvent evt) {
if (power > 0 ){
if (pointsAvailable <= 0) {
JOptionPane.showMessageDialog(null, "You are out of available points");
return;
}
power = power - 1;
pointsAvailable = pointsAvailable +1;
availablePoints.setText(String.valueOf(pointsAvailable));
powerPoints.setText(String.valueOf(power));
}else {
JOptionPane.showMessageDialog(null,"You cannot take anymore points from Power");
}
}
Thank your for your kind replies.

Use a JSpinner with SpinnerNumberModel. Change the value of the model. The component will update and further changes will act on the current value of the model.

I can quickly think of two solutions:
1. In the event handler of your clear button include the following:
private void JButtonActionPerformed(ActionEvent evt){
...
pointsAvailable=40;
speed=0;
power=0;
focus=0;
agility=0;
defence=0;
attack=0;
}
This will reset all of your stats.
2. Or you can add an if statement to the listeners of every button that adds or subtracts a stat that will check if the specific statistic is empty. For example, for the speed buttons the code would look like so:
if (speedPoints.getText() == ""){
pointsAvailable += speed;
speed = 0;
}

Found my own solution on google:
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
speedPoints.setText(String.valueOf(0));
powerPoints.setText(String.valueOf(0));
agilityPoints.setText(String.valueOf(0));
defencePoints.setText(String.valueOf(0));
focusPoints.setText(String.valueOf(0));
attackPoints.setText(String.valueOf(0));
availablePoints.setText(String.valueOf(40));
}
Works perfectly

Related

Java: Why would a variable set outside of a for loop change inside of the for loop

I am a fairly new programmer working on a game in java (as a side project). I'm learning a lot, and I've managed to create a surprising amount of the game without needing help. I could probably even just omit this function and it wouldn't ruin the aesthetic!
I would like to make it work though, and I am perplexed. I set the tempColor variable outside of a for loop, but it changes inside the for loop... but only the second time it is activated, and only to the variable that was used the first time it ran. For example: If I change the red teams score, it runs through and my JOption shows the red - red match and it changes the red teams score only. If I then change blue teams score, it runs through, finds the blue - blue match changes the score, then goes back through the loop a second time until it finds the red - red "match" and changes that score to the same value as the blue score.
I've been over it top to bottom and I can't find what would cause this! I am hoping someone might take pity on me and help me learn something.
Another action I don't understand, I have a main class variable, Choice, but it wasn't passing into the internal code, so I had to transfer it to the tempColor variable. I also noted that I cannot reset it inside the method (something about needing to be "final." I assumed this is because it is a temporary variable that should not exist after the loop executes, but given the behavior of the program... I"m Not sure if this is important, but thought it might possibly be relevant.
The operation starts with the menu item:
private void mniAdjustScoreActionPerformed(java.awt.event.ActionEvent evt) {
adjustScore();
}
Which runs:
private void adjustScore() {
//FIXME changing the first team AND the second team's score when called a second time for some unknown reason... an unexpected loop?
//set components visibility
df.CT.lblChoose.setText("Which team needs adjustment?");
setCTButtons();
df.CT.setVisible(true);
df.CT.btnAdjust.setVisible(false);
df.CT.jspAdjust.setVisible(false);
df.CT.txtName.setVisible(false);
//Set Choice color by button and pass to changeScore method
df.CT.btnRedTeam.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Choice = "red";
changeScore();
Choice = "";
}
});
df.CT.btnBlueTeam.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Choice = "blue";
changeScore();
Choice = "";
}
});
df.CT.btnCyanTeam.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Choice = "cyan";
changeScore();
Choice = "";
}
});
df.CT.btnYellowTeam.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Choice = "yellow";
changeScore();
Choice = "";
}
});
df.CT.btnGreenTeam.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Choice = "green";
changeScore();
Choice = "";
}
});
df.CT.btnPurpleTeam.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Choice = "purple";
changeScore();
Choice = "";
}
});
}
Once the button is pressed, it runs the changeScore() method:
private void changeScore(){
//TODO Fix me - running adjust score a second time changes both the second team and the first team. some kind of unintended loop???
//set components visibilty for second part of operation
df.CT.lblChoose.setVisible(true);
df.CT.jspAdjust.setVisible(true);
df.CT.btnAdjust.setVisible(true);
df.CT.txtName.setVisible(false);
//set tempColor to Choice value (LOOK UP LATER - not sure why this is necessary)
String tempColor = Choice;
//adjust button
df.CT.btnAdjust.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
//get value from spinner and assign to tempScore
int tempScore = (Integer) df.CT.jspAdjust.getValue();
//iterate through the teams to find the one whose TeamColor property matches tempColor
for(int i=0; i<df.orderedTeamList.size(); i++){
String tempColor2 = df.orderedTeamList.getElementAt(i).getTeamColor();
//REMOVELATER - option pane to show values in each iteration
JOptionPane.showMessageDialog(null, "Choice: "+ Choice + "\n tempColor: " + tempColor + "\n tempScore: " + tempScore + "\n tempColor2: " + tempColor2,
"NOTE", JOptionPane.ERROR_MESSAGE);
// look for a color match and assign values to the correct team
if (tempColor2.equals(tempColor)){
if (tempColor.equals("red")){
df.txtScoreT1.setBackground(Color.RED);
df.orderedTeamList.getElementAt(i).setTeamScore(tempScore);
}
else if (tempColor.equals("blue")){
df.txtScoreT2.setBackground(Color.RED);
df.orderedTeamList.getElementAt(i).setTeamScore(tempScore);
}
else if (tempColor.equals("cyan")){
df.txtScoreT3.setBackground(Color.RED);
df.orderedTeamList.getElementAt(i).setTeamScore(tempScore);
}
else if (tempColor.equals("yellow")){
df.txtScoreT4.setBackground(Color.RED);
df.orderedTeamList.getElementAt(i).setTeamScore(tempScore);
}
else if (tempColor.equals("green")){
df.txtScoreT5.setBackground(Color.RED);
df.orderedTeamList.getElementAt(i).setTeamScore(tempScore);
}
else if (tempColor.equals("purple")){
df.txtScoreT6.setBackground(Color.RED);
df.orderedTeamList.getElementAt(i).setTeamScore(tempScore);
}
else{
JOptionPane.showMessageDialog(null, "Team is not active!",
"Team Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// refresh point totals and close the CT window
updatePoints();
df.CT.setVisible(false);
}
});
}
I had originally tried to setup a joption dialog to get this info, but I couldn't get it to read. Then I tried passing the color into the method, but it had the same effect I'm experiencing now... well that and it didn't change the score when I had it set up that way. This just seems weird and illogical.
I added the joption pane to track the variables, which is how I found where and what it was doing. I'm just stumped as to what to do with that information!
Also, I'm aware my code is not as efficient as it could be. I'm still learning and applying new techniques as I learn them. I only started working in java like 2 months ago, so my strategy is to make it work then improve it.
Don't dynamically add ActionListeners to your buttons - add them once when creating the components.
What happens is this:
you click the button for the red team. This sets Choice to "red" and calls changeScore()
changeScore() adds an ActionListener to the adjust-button with tempColor having "red"
you click the button to adjust the teams score. The previously added ActionListener for the red team runs and adjusts its score.
you click the button for the blue team. This sets Choice to "blue" and calls changeScore()
changeScore() adds a second ActionListener to the adjust-button with tempColor having "blue"
you click the button to adjust the teams score. Both ActionListeners that you added (one for the blue team, one for the red team) run and adjust the scores of their team.
If you were to click the button for the "cyan" team your could would add a third ActionListener which would then change the scores of three teams.
This fix is - as I've written in the first paragraph: don't dynamically add ActionListeners to your buttons.

one jbutton doing different actions when clicked again

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.

Adding a new button after an event

Writing a program to increment a counter when a +1 button is pressed, then when the counter reaches a certain number, remove the +1 button and replace it with a +2 button and so on. I create both buttons at first but just set btnCount1 to setVisible(false). When the certain number passes, I make btnCount invisible and btnCount1 visible and increment by two from there. When it reaches 10 clicks, the btnCount disappears, but btnCount1 does not appear.
I have tried making an if(arg0.equals(btnCount1)), and incrementing by two from there. I tried putting the add(btnCount1) inside the else if statement to create it after the elseif condition is true.
public class AWTCounter extends Frame implements ActionListener
private Label lblCount;
private TextField tfCount;
private Button btnCount;
private Button btnCount1;
private int count = 0;
public AWTCounter() {
setLayout(new FlowLayout());
lblCount = new Label("Counter");
add(lblCount);
tfCount = new TextField(count + "",10);
tfCount.setEditable(false);
add(tfCount);
btnCount = new Button("Add 1");
btnCount1 = new Button("Add 2");
add(btnCount);
add(btnCount1);
btnCount1.setVisible(false);
btnCount.addActionListener(this);
btnCount1.addActionListener(this);
setTitle("AWT Counter");
setSize(500,500);
}
public static void main(String[]args) {
AWTCounter app = new AWTCounter();
}
public void actionPerformed(ActionEvent arg0) {
if(count <= 10) {
++count; //Increase the counter value
tfCount.setText(count + "");
}else if(count > 10) {
btnCount.setVisible(false);
btnCount1.setVisible(true);
count += 2;
tfCount.setText(count + "");
}
}
The better solution here is to just have one button object and a separate variable for the current increment amount. When you hit the required count, increase the increment amount and change the button's label to the new value.
There are also a few other things you could do better here.
Use String.valueOf() instead of int + "" for String representations of integers if you're not adding words before or after the integer.
Don't add obvious comments for code. (e.g. 'increment variable x', 'set textString to the new value')
Use descriptive names for method parameters and variables.
Use Labels instead of TextFields for text that doesn't need to be editable or selectable like counter displays.
I'd personally change the name of lblCount to something like lblTitle as well, since changing your tfCount to a Label would logically take up that name and lblTitle makes more sense.
Here's a better way to implement actionPerformed:
private int increment = 1;
private Label lblCount;
...
public void actionPerformed(ActionEvent ignore) {
if(count == 10) {
btnCount.setLabel("Add " + (++increment));
}
lblCount.setText(String.valueOf(count += increment));
}

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

actionListener on a JButton created from vector

I've been searching the web for an answer to my specific basic problem, but was unable to find one.
I must say I am new to programming and I have to do this for school.
I have created an interface of a 6/49 lottery, where you have to click 6 JButtons, creating your "lucky" numbers. In my interface .java, I've created my buttons this way:
JButton b;
for (i = 1; i <= 49; i ++)
{
String s = String.valueOf(i);
b = new JButton(s);
if (i % 2 == 0)
b.setForeground(new Color(3, 121, 184));
else
b.setForeground(new Color(228, 44, 44));
choixNumero.add(b);
Note: "choixNumero" is a gridLayout ( 7 x 7 )
In another .java , I'm creating an actionListener to my JButton b, but that doesn't seems to work. Here is how I wrote it:
intProjet.b.addActionListener(new EcouteurCombinaison()); // where "intProjet" is my interface.java
and heres the code of my EcouteurCombinaison:
private int [] nums;
private int nbRestant = 6;
private class EcouteurCombinaison implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (nbRestant > 0)
{
//nums[nbRestant] = indexOf(e)); //will have to find a way to get index of the button pressed
nbRestant --;
intProjet.valNbRestant.setText("" + nbRestant);
}
else
{
JOptionPane.showMessageDialog(null, "Vous avez choisis vos 6 numéros\n Cliquer sur Soumettre pour valider", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
So basically, I'm trying to add the index or the value of my JButton to the vector everytime a button is pushed. I will then send it to another .java
I've implemented others actionListener to my code and they work fine ( JButton, RadioButton, JComboBox ). I don't understand why nothing happens when I click my buttons.
I tried to make this as clear as possible, without pasting all the code.
Edit: The ActionListener works with the last button only ( 49 ). How can I make it listen to all b Buttons ?
intProjet.b refers to the last button created in your loop, so the result is expected. Instead, you can give each button its own instance of a listener, as shown here.
You are continually reassigning the value of b in that loop. When the loop completes, the last JButton to be created is assigned to it. You then bind an ActionListener to that button, but none of the others. I'm not sure why you expected a single invocation of intProjet.b.addActionListener() to add it to all JButtons.

Categories