I have a toggle button and I set its state as follows
public void setSizeFeet(boolean enabled) {
this.size_tb.setSelected(enabled);
}
I have listener
size_tb.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
size_tbStateChanged(evt);
}
});
private void size_tbStateChanged(javax.swing.event.ChangeEvent evt) {
if (size_tb.isSelected()){
size_tb.setText("Feet");
} else {
size_tb.setText("Meters");
}
}
The problem that when I set the state calling the first method. Nothing happens. However, by just hovering the mouse over the button then it updates to show the correct text. I put a break a point and I noticed the event just fires when I hover the mouse over the button. Shouldn't it when the selection is set or when it is mouse click not hover)
Thanks
Use ActionListener:
new JToggleButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton tBtn = (JToggleButton)e.getSource();
if (tBtn.isSelected()) {
System.out.println("button selected");
} else {
System.out.println("button not selected");
}
}
});
Alternatively you can use the ItemListener:
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
System.out.println("Selected");
} else {
System.out.println("Deselected");
}
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.