JText string input, then display output to JList - java

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.

Related

Searching a hashmap using a jtextfield and jbutton

I'm having some trouble getting a search to work correctly. The first thing I'm doing is adding 2 values from 2 separate jtextfields and adding one to key and one to value of a hashmap. This also adds the value to a jlist.
The second is a jtextfield and jbutton that is supposed to search for the key and highlight it's corresponding value in the jlist field.
For the first button's action performed ( the one that adds the value/key ) I have the following code:
if (capitalText.getText().equals("")) {
capitalText.requestFocusInWindow();
} else if (countryText.getText().equals("")) {
countryText.requestFocusInWindow();
} else {
lm.addElement(capitalText.getText());
capitalText.setText(value);
countryText.setText(key);
String key=countryText.getText();
String value=capitalText.getText();
hashMap.put(key,value);
searchButton.setEnabled(true);
}
For the search button I have the following code:
String value=hashMap.get(key);
searchText.setText(search);
if(searchText.getText().equals(key)) {
searchText.setText(search);
String search = (String) jList1.getSelectedValue();
} else {
JOptionPane.showMessageDialog(null,"That search term could not be found","Search Inquiry",JOptionPane.WARNING_MESSAGE);
}
It appears to add and set the value/key, but when I attempt to search it always does the "else" statement and throws the joptionpane.
Are the value/key actually being added correctly? Or is the search not working? Or both?
Thank you for any advice/help!!

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

Making a label editable depending on a variable in an array

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

JComboBox addActionListener does not work

So I have this project,
the source code is here.
When you run the project and goto Processing, there is a jcombobox there that is suppose to have an addActionListener.
p_customer_list = new JComboBox<>(customers_name);
pp_customer_list.setPreferredSize(new Dimension(360, 35));
panel_processing_header.add(pp_customer_list);
//pp_customer_list.addActionListener(this);
pp_customer_list.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
JComboBox tmpBox = (JComboBox) e.getSource();
int selected = tmpBox.getSelectedIndex();
pp_refresh_data(selected);
}
});
This is what I have so far, its suppose to find the selected index when the value of the combobox changes and pass it to pp_refresh_data() but for some reason it does not run (I tried putting a JOptionPane to see when the code is executed, and its only executed once when the program runs.)
Hard to tell from just a partial code snippet, but do you have 2 combos, one named "p_customer_list" and another named "pp_customer_list"?
This could be your problem. You may be adding the listener to the wrong combo, or you may be adding the wrong combo to your panel, or maybe you don't need two, or maybe...
Again, it's hard to tell from just a snippet.

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

Categories