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);
}
}
Related
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.
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
I am making a registration page but I am fairly new to Java, I have a combo box for peoples Titles such as "Mr, Mrs, Miss, etc" one of the options is "Other..." And I have a text field next to the combo box to specify your title, I would like the text field to not be editable unless someone selects "Other..." in the combo box, How would I do this?
What it looks like at the moment:
I can't see what I'm doing wrong?
TitleSpecifyChoiceField.setEditable(false);
TitleSpecifyChoiceField.setText("Please specify title...");
TitleChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other..." }));
TitleChoice.setToolTipText("");
TitleChoice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (TitleChoice.getSelectedItem().equals("Other...")){
TitleSpecifyChoiceField.setEditable(true);
};
You would do this the same way you'd respond to any changes in a JComboBox -- by adding a listener to the JComboBox as per the Swing combo box tutorial. Inside the listener, change the setEnabled(...) setting on the JTextField depending on the selected item. i.e., by calling getSelectedItem() on the JComboBox and testing whether calling equalsIgnoreCase("other") is true.
Note that I recommend that you use setEnabled(...) not setEditable(...) as the former will give the user visual cues as to whether the JTextField should be edited or not.
Edit
Regarding your code:
TitleSpecifyChoiceField.setEditable(false);
TitleSpecifyChoiceField.setText("Please specify title...");
TitleChoice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mr", "Mrs", "Miss", "Ms", "Dr", "Other..." }));
TitleChoice.setToolTipText("");
TitleChoice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
if (TitleChoice.getSelectedItem().equals("Other...")){
TitleSpecifyChoiceField.setEditable(true);
}
}
});
Some problems and issues:
Does your JComboBox use Strings or does it hold other types of items?
You will want to add debugging code into your code to try to isolate the problem. For instance, inside of your ItemListener, add a System.out.println(...) to print out the selected item to be sure that the listener is working as expected.
You are checking if the item .equals("Other..."), a String literal. Instead consider making a String constant, OTHER that the JComboBox uses and that you test in the listener to be sure that the tested String and and the displayed are the same.
Again, I suggest you use setEnabled(...) not setEditable(...).
You should learn and follow Java naming conventions including beginning all variable names with lower case letter as this will help us to better understand your code.
You should fix your posted code indentation so that it is regular and makes sense (note my code above vs yours). Why do you want to make it harder for folks who are trying to help you to understand your code? Your job is to make ours as easy as possible as we're all volunteers.
Create and post an sscce to get the best and fastest help.
Add a listener to the combo box. When the selected item changes, call setEditable() on the text field.
You could try adding an ItemListener to your JComboBox and (as #HovercraftFullOfEels suggested) use setEnabled as opposed to setEditable. For a general idea, you could do something like this:
JTextField textField = ...;
JComboBox<String> comboBox = ...;
comboBox.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
final String selected = (String)comboBox.getSelectedItem();
textField.setEnabled(selected.equals("other"));
}
}
);
Or if you are using Java 8 you could use this:
JTextField textField = ...;
JComboBox<String> comboBox = ...;
comboBox.addItemListener(
e -> {
final String selected = (String)comboBox.getSelectedItem();
textField.setEnabled(selected.equals("other"));
}
);
I need to remove all items from the combo box
int itemCount = combo.getItemCount();
for(int i = 0; i < itemCount; i++){
combo.removeItemAt(0);
}
This code will remove all items except the last one. It gives a NullPointerException.
How to fix that?
The code in the question would normally work. However, it looks like a threading issue. Another thread may be messing with the items.
However, I sugeest you should better use the removeAllItems(); method:
combo.removeAllItems();
How about JComboBox.removeAllItems()?
You can use
this.combo.removeAllItems();
to remove all the items in JComboBox.
In second line:
combo.removeItemAt(0);
I think instead of 0 it should be i.
do it in reverse order as:
for(int i=combo.getItemCount()-1;i>=0;i--){
combo.removeItemAt(i);
}
But in my case combo.removeAllItems() works fine
use .removeAllItems() methods to remove all items from combo box.
The assumption that it is related to another thread is not always true. It can be the thread itself causing the issue.
This exception may happen because an event is triggered when a combo item is removed and in this event handling method you still refer to combobox items.
For example when you delete somewhere (other than in actionPeformed()) in your code the last item from a combo box with combo.removeItemAt(0) or removeAllItems() then still the event actionPerformed will be fired/executed. But very often the actionPerformed() method contains code to react on user actions (user clicked somewhere on the combobox). So, when the last item has been deleted there is no more item in the combobox and any reference to an item or index in actionPerformed() will cause an exception.
The solution to this is to move the code from actionPerformed() to e.g. mouseClicked() or another event handler depending on what you want to do.
removeAllItems() it does remove all things but after the add data to the combo box it will not show there ,the nullPointException will shows
Use this to remove all the elements from the combo box :
DefaultComboBoxModel model = (DefaultComboBoxModel) ComboBox.getModel();
model.removeAllElements();
Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:
jComboBoxExample.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
do_run ();
}
});
public void do_run() {
int n=jComboBoxPerfilDocumentos.getItemCount(); <--THIS IS THE SOLUTION
if (n> 0) {
String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString ();
}
}
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.