How to make a checkbox non-editable in Java? - 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.

Related

How to code if a checkbox is unchecked in 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.

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

JText string input, then display output to JList

I am pretty new in Java programming, I have been trying to solve this simple program
it reads user input, then the ADD button will simply display the typed string on the JList.
The remove button will simply remove the desired item in the JList.
I am quite confused how to put the action listener thing in the code, or get text whatever
it is. I'd really appreciate if you can help me solve this simple GUI.
It reads user input in JText (String) and when I click the add button (maybe action performed?) the String will be basically populated in JList. and the Remove button will
simply remove the selected String in JList.
Step 1
Bind the code to the specific event, using the addActionListener method.
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
// Bind the method to the button.
}
});
Step 2
Populate that method with the relevant code.
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list model that informs the JList.
Altogether
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list.
}
});
Useful Links
Here is a very good tutorial from Oracle detailing how to manipulate lists a million and one different ways.

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);
}
}

Java: Getting a checkbox name from a new JFrame

I have a JCheckBox defined as:
JCheckBox NewCB = new JCheckbox();
NewCB.setSelected(false);
NewCB.setMnemonic(KeyEvent.VK_C);
NewCB.addItemListener(this);
This Check Box is using an ItemLisener:
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if(source == NewCB) {TEST = "SELECTED"; System.out.println(TEST);}
}
I launch a JFrame when the program starts. If I add this CheckBox to the frame, it works fine. If I open a second JFrame, and add this Check Box to the 2nd frame, and the Object Source no longer works. Is there some other definition I need to make to get the Object source to read the check box name for any open frames?
First of all, you can't add a component to more than one parent; I'm not sure that's your problem though.
The thing you're calling the "name" of the checkbox isn't a property of the checkbox, but rather a property of a variable that points to the checkbox. The difference is important, because there could be many such variables. The checkbox doesn't know anything about the variables that point to it.
Given that, how do we solve the problem? You can set the "action command" of the checkbox, and then check that:
NewCB.setActionCommand("Fred");
// ...
if ("Fred".equals(((JCheckBox) source).getActionCommand())))
// ...

Categories