How to code if a checkbox is unchecked in java - java

Currently, I'm developing a Restaurant management system in java. when I check a checkbox it will add money to the total amount, all I want to know that if I uncheck that checked checkbox again then it will subtract that added amount again. following is my checkbox code
private void jcbWPizzaMouseClicked(java.awt.event.MouseEvent evt) {
double cMeal = Double.parseDouble(jlblCostOfMeal.getText());
double WavePizza = Double.parseDouble(jtxtWP.getText());
double iWavePizza = 350;
if (jcbWPizza.isSelected()) {
i[1] = (WavePizza * iWavePizza) + cMeal;
String pMeal = String.format("%.2f", i[1]);
jlblCostOfMeal.setText(pMeal);
}
}

if you are using JCheckBox there is a method boolean isSelected() so to verify whether the JCheckBox is selected you can try :
if (checkbox.isSelected()) {
// selected, do something...
} else {
// un-selected, do something else...
}

You want to change the value of total amount based on the object jcbWPizza's selected stated. you can add ItemListener to the checkbox
jcbWPizza.addItemListener(new ItemListener() {
#Override public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
//checkbox has been selected //do selected action...
} else {
//checkbox has been deselected //do deselected action...
};
}
})

Your question raises a number of issues that you might not have thought about.
Firstly, by relying on a MouseEvent, you will not capture those times when the checkbox changes state due to some other reason (for example, by code, or if the user uses the keyboard to change selection). Adding an ItemListener would be a more generation approach.
In the future, there might be a number of other things that affect the price. Having the code that updates the price hidden in this checkbox listener seems like the wrong approach. What would be better is to add a listener that just calls a general "update the displayed price" method. Within that method, you could then check the state of each of the widgets that will affect the final price and calculate accordingly. It then doesn't matter if the checkbox is or was hidden or not, as each time it is asked to update, it will calculate the total from scratch.
Finally, bear in mind that Swing is not thread-safe. Whilst a single Thread will call your listeners, there is no guarantee that only a single Thread will be calling your "recalculate the price" method. Ensure that if more than one Thread should call your code at the same time, you don't end up getting your state out of sync. Avoiding a "the checkbox has been toggled, so add or subtract" logic is a good idea once again, as it adds additional state that needs to be kept in sync.

Related

Is there a way to update a variable outside a method that is used as a parameter in said method?

I have 62 check boxes on 2 different panels.
30 of them on each panel are for selecting PC names while 1 on each selects all.
So on each of those 60 that are just selecting items I have this code:
private void HP04ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
setComponent(HP04, blrS,all_blr);
HP04 is the name of a checkbox for one of the PCs, blrS is the name of an int that counts how many checkboxes are selected(there is another int for the boxes on the other panel), all_blr is the name of the checkbox that selects all on the blr panel.
This is the method I used:
public void setComponent(javax.swing.JCheckBox component, int room,javax.swing.JCheckBox all)
{
System.out.println("Inside Component: "+component.isSelected()); //testing to see if the method is actually being called
if (component.isSelected()){ //if checkbox is checked
room++; //records how many boxes are checked
if (room == 30)
{
all.setSelected(true);//autochecks "all" check box if all PCs are selected
}
if (!messagearea.getText().equals(""))
{
sendb.setEnabled(true);//if any boxes are checked and the message area is populated, enable the button
}
}
else
{
room--;//records how many boxes are checked
all.setSelected(false);//unchecks the "all" check box if not all of them are checked
if (room == 0)
{
sendb.setEnabled(false);//disables button if no PCs are selected to be messaged
}
}
System.out.println(room); //testing int updates based on UI changes
}
Now the problem is room is only fetching the value of whatever variable is put in that parameter and then room itself is being modified. So in the example setComponent(HP04, blrS,all_blr); blrS is never changed.
I know the code inside the method works, it worked before I decided to cut down on code by using a method, as before I had the code inside the method in the actionperformed for every checkbox before hand... Like this:
private void HP04ActionPerformed(java.awt.event.ActionEvent evt) {
if (HP04.isSelected()){
blrS++;
if (blrS == 30)
{
all_blr.setSelected(true);
}
if (!messagearea.getText().equals(""))
{
sendb.setEnabled(true);
}
}
else
{
blrS--;
all_blr.setSelected(false);
if (blrS == 0)
{
sendb.setEnabled(false);
}
}
System.out.println(blrS);
}
It's just understanding how parameters and methods works that is tripping me up.
It feels obvious that what I'm doing shouldn't work, room is a variable inside the method... But how do I change that?
Solution found:
"Why not return room from the method, and assign it to the variable when you call it? blrS = setComponent(HP04, blrS, all_blr);"
– Rob Spoor (in the comments to this post)

Java Checkbox Action

I have a check box and when I create an Action script from the Netbeans' design, it creates a function like;
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
total=8.99f;
xc = "XCheese";
exTop++;
calculateTotal(total);
updateTextArea();
}
This works perfectly, but I want to set everything to zero when the jCheckBox1 is unchecked, if I uncheck it the way the code is now, no changes appear.
It is an sample of code. Hope it will help you.
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if(checkBox.isSelected() ){
total=8.99f;
xc = "XCheese";
exTop++;
calculateTotal(total);
updateTextArea();
}else{
// set everything zero here.
}
}
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons
Basically, the ActionListener will be called when ever the check box is selected (checked) or unselected (unchecked). You need to check the state of the check box when ever the method is called.
Take a look at AbstractButton#isSelected which will tell you the (in this case) the checked state of the JCheckBox

How to insert items to a jcombobox at runtime and save it

I need to save the values in my jcombobox at the runtime. What I am trying to do is after clicking on a button, I am setting it to editable = true. Then type the value in the combobox, but it doesn't save.
private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()== btadbkname){
cb_bkname.setEditable(true);
cb_bkname.getText();
cb_bkname.addItem(evt);
}else{
cb_bkname.setEditable(false);
}
}
I have already added some elements in it on the designing level, but it's limited if some random value comes then its a problem.
Because it is possible to add / remove Item(s) to / from the DefaultComboBoxModel underlaying the JComboBox, the same action (by default) is possible from outside.
You have to use MutableComboBoxMode to add / remove Item(s) to / from JComboBox that fires event from itself (view_to_model).
There are excellent examples of MutableComboBoxModel by #Robin here and here.
For better help sooner post an SSCCE, for future readers, otherwise search for extends AbstractListModel implements MutableComboBoxModel.
it can't possibly work the way you're trying it.
the comboBox has to be editable before you click the button then you just need this line
cb_bkname.addItem(((JTextField)cb_bkname.getEditor().getEditorComponent()).getText());
Try this
private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource()== btadbkname){
cb_bkname.setEditable(true);
String newItem=cb_bkname.getText();
cb_bkname.addItem(newItem);
}else{
cb_bkname.setEditable(false);
}
}

How to make a checkbox non-editable in Java?

I have a checkbox. I will obtain one value from a database to determine whether the checkbox can be edited or not. If this value is zero, the checkbox should not be selected. How do I achieve that in code? Please help me out here. This is my code:
String status = "0"; // (obtained from the database)
if(status)
{
// should not be editable - can't be selected.
} else {
// can be selected.
}
If this is REALLY what you want to do instead of using a JLabel with appropriate text and/or icon, you can create an action listener for the checkbox and have it call setSelected:
// the action listener for the checkbox
private void myCheckBoxActionPerformed(java.awt.event.ActionEvent evt)
{
if (status.equals("0")
myCheckBox.setSelected(false);
else
myCheckBox.setSelected(true);
}
To say the least, this isn't an elegant solution, but it does give the appearance that the checkbox isn't editable.
Use the setEnabled method for that.

JCheckBox' value resets / doesn't change

I have several components, all inheriting JCheckBox without overwriting anything from it, stored in a vector, which is then traversed and each of the components is added to a dialog
CreateLists(); // initialises the checkbox vector
for(int i = 0; i < checkBoxes.size() ; i++){
myPanel.add(checkBoxes.elementAt(i));
}
Some of these checkboxes are already selected.
My problem now is: When I open the dialog and select or unselect any checkbox, the value of the checkboxes in the vector doesn't change. Selected stays selected and unselected stays unselected.
I also tryed to get the new values by using JPanels getCompoents(), but the values of these are wrong, too.
An ItemListener in the checkbox inheritors confirmes that the changes do happen, but whenever I try to get the new values, there just the same as those with which the checkboxes were initialised.
Here is a console output I used to keep track of the changes:
create lists
print values:
checkBox1 = true
checkBox2 = true
checkBox3 = false
checkBox2 clicked new value = false
checkBox3 clicked new value = true
print values:
checkBox1 = true
checkBox2 = true
checkBox3 = false
Here is some more code and information:
CreateList() compares a watchlist with the watchable things, creates the checkboxes accordingly (true = watched etc) and adds them to the new initalised vector.
To read the values i use this:
Component[] components = pnlGesamt.getComponents();
for(int i = 0; i < components.length; i++){
if(components[i] instanceof WLElementCheckBox){
WLElementCheckBox cb = (WLElementCheckBox) components[i];
System.out.println(cb.WlElement().Name() + " = " + cb.isSelected());
}
}
The JCheckBox inheritor:
private WatchListElement wlElement;
public WLElementCheckBox (WatchListElement wl, boolean selected)
{
super();
WlElement(wl);
setSelected(selected);
setText(wlElement.Name());
addItemListener(new MIL());
}
public WatchListElement WlElement ()
{
return wlElement;
}
public void WlElement (WatchListElement wlElement)
{
this.wlElement = wlElement;
}
public class MIL implements ItemListener{
public void itemStateChanged(ItemEvent arg0) {
System.out.println("Ckb " + wlElement.Name() +" geklickt Item neu = " + isSelected());
}
}
There is a small possibility that the changes to your checkboxes are not visible because you're querying them from another thread (such as main) instead of the Event Dispatch Thread (EDT). Swing is not thread-safe. When you check the checkboxes, the values are set on the EDT, but other threads might have the old state saved in memory and don't check to see if it's been updated. So, the first thing you need to do is ensure that when you're checking the states of your checkboxes, you're doing it from the EDT, using a call to SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater().
For more information on why this happens, search for Thread Safety in Java.
(Also, don't be tempted to use synchronization to solve the problem or you might end up with a deadlock in your GUI).
One final pro tip: using new Java for-loop syntax makes code easier to read and write, as well as more efficient in some cases. Your code...
for(int i = 0; i < checkBoxes.size() ; i++){
myPanel.add(checkBoxes.elementAt(i));
}
... can turn into...
for(JCheckBox c : checkBoxes) {
myPanel.add(c);
}
This works on arrays and anything that is Iterable (which includes Collection).

Categories