I have a combo box and a string array that holds all the values of the combo box in it. I erase the items from the combo box and then want to add in the values from the string array. It doesn't seem to let me just add in a string array. And I tried to itterate through the string adding items one by one but won't let me do that (or atleast the way I wrote it, it won't work).
May seem like a stupid question but I am new to working with swing in java.
Here's the code where I want to "reload" the items from the combo box:
String str = JOptionPane.showInputDialog(null, "Enter Name: ", "", 1);
if(str != null){
JOptionPane.showMessageDialog(null, "New name added: " + str, "", 1);
nameCreator.addName(strNames, str);
strNames = NameLoader.getNames();
nameList.removeAllItems();
nameList.addItem(strNames);
}
EDIT: Made small typo and didn't realize what was wrong. Working now. Thanks for everyones help.
Did you used the method addItem(Object anObject)?
You should iterate your array an use that method:
String[] data = {a;b;c;d;e}
for(int i=0; i < data.length; i++){
comboBox.addItem(data[i]);
}
Luca
I'd suggest you to implement your own ComboBoxModel:
public class YourComboBoxModel implements ComboBoxModel{
#Override
public Object getSelectedItem() {
//return selected item Object;
}
#Override
public void setSelectedItem(Object anItem) {
//set selected item
}
#Override
public Object getElementAt(int index) {
//return the element based on the index
}
#Override
public int getSize() {
//return the size of your combo box list
}
}
And build your JComboBox passing that model as parameter:
ComboBoxModel yourModel = new YourComboBoxModel();
JComboBox yourComboBox = new JComboBox(yourModel);
Using a custom ComboBoxModel is the most flexible solution. It allows you to change the datastructure holding your datas, and the way you access it, modifying only the model you implemented instead of other unrelated part of code.
Whenever you need to work with editable models for these kinds of GUI elements it is always good to use a model. For the JComboBox you have an easy-to-use DefaultComboBoxModel.
It works easily:
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[]{"Item1","Item2","Item3"});
JComboBox comboBox = new JComboBox(model);
in this way you have the model attached to the combobox, and it will display items from the array. Whenever you need to change them just do:
model.removeAllElements(); // if you need to empty it
model.addElement("New Item1");
model.addElement("New Item2");
model.addElement("New Item3");
model.fireContentsChanged();
and you'll have new items updated inside the GUI.
A bonus note: if you need to manage custom objects instead that strings you can easily add them to the JComboBox (in the sameway showed before), you just need to provide a custom public String toString() method that will manage the string representation.
In your example I don't get why you readd all the items everytime, you could just call addItem with the new String without removing everything and adding them back.
the best way to add some thing in your combo box in order that you can change it easily is to describe an array list first,if you would like to be dynamic you can user a text field then in a text field you can run an array list .
textField = new JTextField();
textField.setBounds(131, 52, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
then you have to create an array list
ArrayList al=new ArrayList();
then you have to equal your text field text to a string
String str=textfield.getText();
then add it to your array
al.add(str);
then add al item to your combo box.
JComboBox comboBox = new JComboBox();
comboBox.setBounds(112, 115, 145, 20);
contentPane.add(comboBox);
comboBox.addItem(al);
Related
I'm designing a project about cataloging something. In this project user must be able to create his own table as he wish. Therefore I do not have any static class and instance of it.
I'm creating a diaglog pane and I can create textfields for user inputs according to column names of database table dynamically but how can i add those user's inputs into the tableView ?
As I can add any String input into the ListView can I add user String inputs into tableView columns?
ListView<String> listView = new ListView();
public ObservableList<String> listCatalogNames = FXCollections.observableArrayList();
listCatalogNames.add("Books");
More details with an example;
There is listview that contains all catalog names and according to lisview selection tableview will be created dynamically center of borderpane.
User have books(name, author, page) and movies(name, year, director, genree) catalogs.
Lets say user selected movies and tableView appeared with 4 columns and clicked add button. Diaglog pane created with 4 textfield. I built everything until that point but I cannot add user's input into the tableView because i dont have any static class for Movies or Books etc.
Is there any way to create dynamic class ?
Please give me an idea and help me about that situation.
here is the github link of our project
Just use String[] storing the Strings for every column of a row (or a similar data structure) as item type for the TableView. It should be simple enough to create a String[] from the inputs and add it to this TableView:
static TableView<String[]> createTable(String... columnNames) {
TableView<String[]> table = new TableView<>();
for (int i = 0; i < columnNames.length; i++) {
final int index = i;
TableColumn<String[], String> column = new TableColumn<>(columnNames[i]);
column.setCellValueFactory(cd -> new SimpleStringProperty(cd.getValue()[index]));
table.getColumns().add(column);
}
return table;
}
Adding a String[] userInputs to a TableView<String[]> table would be done like this:
table.getItems().add(userInputs);
A similar issue (creating a TableView based on the metadata of a ResultSet) can be found here: How to fill up a TableView with database data
Easiest solution that comes to my mind is to make use of polymorphism. You can create a super class of both Book and Movie, let's call it Item. Then you can declare your table to contain Item and cast to one of the concrete classes when you need to.
I am trying to make a Swing GUI in Netbeans. I create a jcombobox and I bind it (using a query component, a list component and a renderer) to an entity called 'Item', so that the combobox shows the names of the items that currently exist in the table "Item" and so far it works fine. However, I need to add an "All Items" field to the combobox. Does anybody have any hints on where I should start?
Try
List<String> listItems = classDAO.findElement();
DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel();
for(String string : listItems)
{
comboModel.addElement(string);
}
comboModel.addElement("All items");
JComboBox<String> comboBox = new JComboBox<>(comboModel);
You can manually add an item to the combo box after the items from the table have been added to the combo box:
comboBox.addItemAt("All Items", 0);
will insert a new item at the top of the combo box.
This question already has answers here:
Why is itemStateChanged on JComboBox is called twice when changed?
(10 answers)
Closed 6 years ago.
I've built a combobox that is dynamically populated depending on the contents of another combobox, and so on. I've decided, although it's a bit terrible, to experiment with iterating through the contents of the source array when populating the target combobox. However, although this results in combobox contents, they are repeated. I've stepped through the code, and the array is only being iterated through once.
private JComboBox regBuildingSelectBox;
...
String[] siteSelectStrings = {"Site", "London", "Long Island"};
JComboBox regSiteSelectBox = new JComboBox(siteSelectStrings);
regSiteSelectBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
getDropDownVariables gddv = new getDropDownVariables();
for(String s:
gddv.buildingSelectList
(regSiteSelectBox.getSelectedItem().toString()))
{
regBuildingSelectBox.addItem(s);
}
}
});
regSiteSelectBox.setBounds(24, 336, 282, 20);
contentPane.add(regSiteSelectBox);
regBuildingSelectBox = new JComboBox();
regBuildingSelectBox.setBounds(24, 367, 282, 20);
contentPane.add(regBuildingSelectBox);
The code containing the arrays is as follows:
public class getDropDownVariables {
public String[] buildingSelectList(String site)
{
switch (site)
{
case "London":
return new String[] {"Building", "Harvell",
"LYNX Complex", "Caroline", "Salters"};
case "Long Island":
return new String[] {"Building", "Phillips", "Pascal"};
}
return new String[] {"Failed to populate buildings"};
}
And the result:
Just a guess, but before you call regBuildingSelectBox.addItem(s); you probably have to clear it first, otherwise it just keeps adding to the list rather than replacing it. There allso might be a different method that sets the values vs adding.
Here's the thing:
I created a 'cocktailbar' software, and I have the following classes:
Cocktail,
CocktailBar,
CreateNewCPanel,
HelloPanel,
SearchCPanel,
ShowAllCPanel,
CocktailMixerGUI,
Ingredients.
Now: When adding a new Cocktail in the CreateNewCPanel, I add the cocktail to a List in the CocktailBar class.
Box buttonBox = Box.createHorizontalBox();
JButton speicherButton = new JButton("Speichern");
speicherButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
neuerC.setCName(cName.getText());
neuerC.fuegeZubereitungHinzu(zubereitungTextArea.getText());
CocktailBar.addCocktail(neuerC);
Now I need to see all created cocktails in a 'dropdown' menu in the ShowAllCPanel. I've got the following:
//Adding the DropDown Menu, first a Box, then a ComboBox inside.
Box cDropDownBox = Box.createHorizontalBox();
cDropDownBox.add(Box.createHorizontalGlue());
JComboBox cChoose = new JComboBox();
groesseEinsetzen(cChoose, 500, 20);
cChoose.setAlignmentX(SwingConstants.LEFT);
cDropDownBox.add(cChoose);
But now I am wondering how do I get my List from the CocktailBar class into the ShowAllCPanel?
edit: forgot to mention: i have a getter in the CocktailBar class, and i already tried:
cChoose.addItem(CocktailBar.getCocktails());
within the comboBox in the ShowAllCPanel, but it doesnt show up anything in the dropdown.
thanks to #Do Re, i inserted this:
//Adding the DropDown Menu, first a Box, then a ComboBox inside.
Box cDropDownBox = Box.createHorizontalBox();
cDropDownBox.add(Box.createHorizontalGlue());
JComboBox cChoose = new JComboBox();
if (CocktailBar.getCocktails() != null){
for (Cocktail c : CocktailBar.getCocktails())
cChoose.addItem(c);
}
but still - when running, the dropdown list stays empty.
As you mentioned in the comments, you created a getter for the cocktails.
Try something like this
for (Coctail c : CocktailBar.getCocktails())
cChoose.addItem(c);
This iterates over the list of cocktails and adds each item seperately rather than adding a list of Cocktails at once.
Edit
try
cDropDownBox.revalidate();
cDropDownBox.repaint();
or
cChoose.revalidate();
cChoose.repaint();
I have an ArrayList<JCheckBox> that i want to convert to an ArrayList<String>
First I do like this. I get all my titles from a file and put them into a new ArrayList. Afterwords I make a new JCheckBox Array that contains all the Strings from the StringArray.
ArrayList<String> titler = new ArrayList<String>();
titler.addAll(FileToArray.getName());
ArrayList<JCheckBox> filmListe = new ArrayList<JCheckBox>();
for(String titel:titler){
filmListe.add(new JCheckBox(titel));
}
for(JCheckBox checkbox:filmListe){
CenterCenter.add(checkbox);
}
This is what I am trying to do: First I make a new ArrayList (still in the JCheckBox format), that contains alle the selected Checkboxes. Afterwords I want to add the to a new ArrayList in a String format.
The main problem is italicized (with **):
ArrayList<JCheckBox> selectedBoxes = new ArrayList<JCheckBox>();
for(JCheckBox checkbox: filmListe){
if (checkbox.isSelected()){
selectedBoxes.add(checkbox);
}
ArrayList<String> titlesArr = new ArrayList<String>();
for(JCheckBox titel:selectedBoxes){
*titlesArr.add(titel);*
}
A lot of code and text for a little problem! But I really appreciate your help! :)
You can't add a JCheckBox to a List<String>, the types JCheckBox and String are incompatibles.
I guess you want to add the text of the check box into your list, so you have to retrieve it manually, using:
titlesArr.add(titel.getText());
Assuming the checkbox's label is exactly the same as what you originally had in your list of titles, just use the checkbox's getText method (which gets the String label). You don't need to make a separate list of checkboxes that are checked - just put an if-block inside your first loop like this:
ArrayList<String> titlesArr = new ArrayList<String>(filmListe.size());
for (JCheckBox checkbox : filmListe) {
if (checkbox.isSelected()) {
titlesArr.add(checkbox.getText());
}
}
Try this:
ArrayList<String> titlesArr = new ArrayList<String>();
for(JCheckBox checkbox: filmListe)
if (checkbox.isSelected())
titlesArr.add(checkbox.getText());
Now titlesArr contains what you wanted.