Working with check boxes in java!
SLVIKI
10:51 AM
0
This is a simple program that uses Java check boxes. To include java check boxes to the program we need to use JCheckBox component. So this program is a demonstration of check boxes using in java.
Here is the code of the simple check box program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | // Demostrate check boxes. import java.awt.*; import java.awt.event.*; import javax.swing.*; class CBDemo implements ItemListener { JLabel jlabSelected; JLabel jlabChanged; JCheckBox jcbAlpha; JCheckBox jcbBeta; JCheckBox jcbGamma; CBDemo () { // Create a new JFrame container. JFrame jfrm = new JFrame("Demonstrate Check Boxes"); // Specify FlowLayout for the layout manager. jfrm.setLayout (new FlowLayout()); // Give the frame an initial size. jfrm.setSize(280, 120); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create empty labels. jlabSelected = new JLabel(""); jlabChanged = new JLabel(""); // Make check boxes. jcbAlpha = new JCheckBox("Alpha"); jcbBeta = new JCheckBox("Beta"); jcbGamma = new JCheckBox("Gamma"); // Events generated by the check boxes // are handled in common by the itemStateChanged() // method implemented by CBDemo. jcbAlpha.addItemListener(this); jcbBeta.addItemListener(this); jcbGamma.addItemListener(this); // add check boxes and labels to the content pane. jfrm.add(jcbAlpha); jfrm.add(jcbBeta); jfrm.add(jcbGamma); jfrm.add(jlabChanged); jfrm.add(jlabSelected); // Display the frame. jfrm.setVisible(true); } // This is the handler for the check boxes. public void itemStateChanged(ItemEvent ie) { String str = ""; // obtain a reference to the check box that // caused the event. JCheckBox cb = (JCheckBox) ie.getItem(); // report that check box changed. if(cb.isSelected()) jlabChanged.setText(cb.getText() + " was just selected."); else jlabChanged.setText(cb.getText() + " was just cleared."); // report all selected boxes. if(jcbAlpha.isSelected()) { str += "Alpha "; } if(jcbBeta.isSelected()) { str += "Beta "; } if(jcbGamma.isSelected()) { str += "Gamma "; } jlabSelected.setText("Selected check boxes: " + str); } public static void main(String args[]) { // create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new CBDemo(); } }); } } |
This is the output of the above simple program
If you have any questions, feel free to ask!
Enjoy!
No comments