Add MouseListener to JCheckBox
I wrote this code for alert message shown to user when they uncheck the checkbox. It only woks when I mouse key is realized with in the checkbox. If user click the checkbox and release out of the checkbox it allow user to uncheck the checkbox and doesn't shows alert message. How can I solve this bug?
public void mouseClicked(MouseEvent e) {
Vector matNoVect = new Vector();
if (e.getClickCount() == 1) {
Utools.setMouseBusy(sstEndProductMaterials.table);
try {
Vector v = new Vector();
v = Inter.LoadContents(str);
System.out.println(v);
if (v.size() > 0) {
if (Integer.parseInt(v.get(0).toString()) > 0) {
JOptionPane.showMes开发者_StackOverflow中文版sageDialog(null,"Material "+matNo+" is used in some Item");
sstEndProductMaterials.table.setValueAt(new Boolean(true),index, 7);
Utools.setMouseNormal(sstEndProductMaterials.table);
return;
}
}
} catch (Exception e11) {
e11.printStackTrace();
Utools.setMouseNormal(sstEndProductMaterials.table);
}
}
}
Use an ItemListener instead of a MouseListener
http://download.oracle.com/javase/tutorial/uiswing/components/button.html#checkbox
You can then do this inside the ItemListener:
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.DESELECTED) {
//Code to show alert etc.
}
}
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
/** Some users are NOT addicted to the mouse! Which is why
it would be better to add an ActionListener to a JCheckBox. */
class CheckBoxTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JPanel p = new JPanel(new GridLayout(0,1,20,20));
JCheckBox cb1 = new JCheckBox("Broken on keyboard");
cb1.addMouseListener( new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent me) {
System.out.println("Mouse click");
}
} );
p.add( cb1 );
JCheckBox cb2 = new JCheckBox("Works for keyboard or mouse!");
cb2.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Event detected!");
}
} );
p.add( cb2 );
JOptionPane.showMessageDialog(null, p);
}
};
SwingUtilities.invokeLater(r);
}
}
精彩评论