JCheckboxMenuItem not working as expected
I have create a popup menu and on right click in a panel the menu is displayed. But when i click the menu item the checkbox doesnt get selected. Here is the code:
public class DebugMenu extends JPopupMenu implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("inside action");
AbstractButton aButton = (AbstractButton) e.getSource();
System.out.println(aButton.getText() +" " +aButton.getMode开发者_如何转开发l().isSelected());
aButton.getModel().setSelected(!aButton.getModel().isSelected());
}
public DebugMenu(){
JMenuItem menuItem = new JCheckBoxMenuItem("2");
add(menuItem);
menuItem.addActionListener(this);
menuItem = new JCheckBoxMenuItem("1");
add(menuItem);
menuItem.addActionListener(this);
}
}
And the Panel class
public class TestPanel implements MouseListener{
public TestPanel(){
JFrame frame = new JFrame("TEST");
frame.setSize(400,400);
frame.addMouseListener(TestPanel.this);
frame.setVisible(true);
}
public static void main(String args[]){
new TestPanel();
}
public void mouseReleased(MouseEvent e) {
DebugMenu menu = new DebugMenu();
if(e.isPopupTrigger()){
System.out.println("trigger");
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
public void mousePressed(MouseEvent e) {
DebugMenu menu = new DebugMenu();
if(e.isPopupTrigger()){
System.out.println("trigger");
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseClicked(MouseEvent e) {
DebugMenu menu = new DebugMenu();
if(e.isPopupTrigger()){
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
what i am doing wrong ?
Well I imagine that aButton.isSelected()
returns true when you have clicked on it, so that the negation turns off the selection. Try using this instead:
public void actionPerformed(ActionEvent e) {
((JCheckBoxMenuItem) e.getSource()).setSelected(true);
}
I figured it out ... I should not be creating the DebugMenu object inside the mouseEvents...
精彩评论