Reputation: 115
I'd like to mute my music player player
using player.mute()
when the JCheckBox mutemusic_box
is checked.
If its unchecked and the player
is muted, the command player.mute()
should execute. How to get this working? My code currently does not work (may because of the ActionEvent).
The check if it's checked or not is in actionPerformed
.
private JCheckBox pwremember_box, mutemusic_checkbox;
//GUI setup
public void actionPerformed(ActionEvent ae) {
if (mutemusic_checkbox.isSelected()) {
System.out.println("Muted!");
player.mute();
}
else {
System.out.println("Unmuted!");
player.mute();
}
}
Upvotes: 2
Views: 2079
Reputation: 131346
First this check is not required :
if (ae.getSource().equals(mutemusic_box)) {
The ActionListener
should be associated to the JCheckBox
button.
So, there is not any ambiguity.
Then in order to know if the checkbox is checked, use simply the isSelected()
method that is designed for.
Besides mute()
is not a good named method to toggle the sound of the Player
.
toggleSound()
could make more sense.
And as explained in my comment, you have to attach first the listener to the JCheckBox.
Here is a sample code :
checkBoxMute.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae) {
if (checkBoxMute.isSelected()) {
System.out.println("Muted!");
player.toggleSound();
}
else {
System.out.println("Unmuted!");
player.toggleSound();
}
}
});
And here the same thing with a lambda instead of creating an anonymous class of ActionListener
:
checkBoxMute.addActionListener(
ae -> {
if (checkBoxMute.isSelected()) {
System.out.println("Muted!");
player.toggleSound();
} else {
System.out.println("Unmuted!");
player.toggleSound();
}
});
}
Upvotes: 4
Reputation: 15842
You can use isSelected
method.
boolean isChecked = mutemusic_box.isSelected();
As a personal advice, rename mutemusic_box
to muteMusicCheckBox
or similar.
Upvotes: 1