How do I change the increment of a button through another button?

2

I have a button that adds a variable: x + 1 , and every time I click this button, the variable will increase by 1 unit.

But how do I program a button to change the function of button 1, so that instead of x + 1 , be x + 2

The buttons, and all of these, are being programmed in Java JFrame with the program netBeans .

private int xi;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         



    xi++;
    jLabel2.setText("Your money  " + xi + "$");

}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    //E neste butao que quero fazer a funcao.


}
    
asked by anonymous 21.06.2016 / 19:09

2 answers

4

One of the ways to do this would be to use a unique variable to represent the "increment":

private int xi = 1;
private int increment = 1;

Then, on the first button, you change to the following:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    xi += increment;
    jLabel2.setText("Your money  " + xi + "$");

} 

And on the second button:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 

    increment = 2;//ou increment++;
    //desativa o botao apos o primeiro uso
    ((JButton) evt.getSource()).setEnable(false); 

}

The way you are, you do not even have to disable the button, however much you click it, the change will always be to 2. If you use increment++ , you must use the code that disables the button to stop incrementing. / p>     

21.06.2016 / 19:42
2

Man, you can use a variable to do this! It's very simple:

private int xi;
private int xi2=1;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    xi+=xi2;
    jLabel2.setText("Your money  " + xi + "$");
}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    xi2+=1;//aqui você muda o tanto que vale, é só adicionar mais um, no caso depende do que você quer adicionar,
    //se você mudar o valor aqui, pode colocar + 150 até, que aí a cada clique vai adicionar + 150
}
    
21.06.2016 / 19:45