4
I’m a beginner in java and I’m having a hard time making the button btnVolumeUp
raise the counter.
First I have this TV class where I created the methods.
public class Televisor {
int canal = 0;
int volume = 0;
boolean ligar = false;
public int diminuiVolume(){ //Diminui o volume da TV
//Se o volume estiver no 0 Exibe msg e não diminui mais
if (volume == 0){
JOptionPane.showMessageDialog(null, "O volume está no minimo");
}
else{
volume--;
}
return this.volume;
}
public int aumentaVolume(){ //Aumenta o volume da TV
//Se o volume estiver no 10 Exibe msg e não aumenta mais
if (volume == 10){
JOptionPane.showMessageDialog(null, "O volume está no máximo");
}
else{
volume++;
}
return this.volume;
}
And then I have a jFrame with the volume buttons and a label to display the current volume. But the button only works the first time. Example: When you first click on btnVolumeUp
the count goes from 0 to 1, but after that nothing else happens.
private void btnVolumeUpActionPerformed(java.awt.event.ActionEvent evt) {
Televisor controle = new Televisor();
String exibeVolume;
exibeVolume = String.valueOf(controle.aumentaVolume());//Converte valor Int para String
lblVolume.setText(exibeVolume);//Altera o volume exibido
}
private void btnVolumeDownActionPerformed(java.awt.event.ActionEvent evt) {
Televisor controle = new Televisor();
String exibeVolume;
//controle.aumentaVolume();
exibeVolume = String.valueOf(controle.diminuiVolume());//Converte valor Int para String
lblVolume.setText(exibeVolume);//Altera o volume exibido
}
That my logic is wrong ?
That’s because every time the method
btnVolumeUpActionPerformed
is called this is creating a new instance of TV, Initiating the value ofvolume
. The object TV should be instantiated outside that method.– ramaral
So in this case I would have to instantiate the TV class out of the buttons ?
– IgorS
I was editing my comment to refer to that.
– ramaral
I just tested here and it worked perfectly. Thank you !!!
– IgorS