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.
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.
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 am writing a Java program and I ran into a problem. I have an ArrayList<JCheckBox> and I want to show some dialog window with these checkboxes, so I can choose some of them and I want another ArrayList<> of the selected objects as an outcome after closing that dialog. I think I can get results by adding ActionListener to those checkboxes, but I donĀ“t know how to pass that ArrayList<JCheckBox> to the dialog window..
So far I tried something like this:
ArrayList<JCheckBox> al = new ArrayList<JCheckBox>();
for (MyClass mc : sr.getFields().values())
{
JCheckBox box = new JCheckBox(mc.getType());
al.add(box);
}
JOptionPane.showConfirmDialog(null, al);
If I try to print the text in the checkbox, it is ok, but the dialog shows only a long line of some text that does not make any sense..
So, is there a way how to do that?
Thanks in advance..
The showConfirmDialog method has to interpret the message object in order to render it correctly and it doesn't know how to interpret an ArrayList, you have to add all your elements to an JPanel eg:
JPanel al = new JPanel();
for (MyClass mc : sr.getFields().values()){
JCheckBox box = new JCheckBox(mc.getType());
al.add(box);
}
JOptionPane.showConfirmDialog(null, al);
or an Object[] eg:
ArrayList<JCheckBox> al = new ArrayList<JCheckBox>();
for (MyClass mc : sr.getFields().values()){
JCheckBox box = new JCheckBox(mc.getType());
al.add(box);
}
Object[] obj = (Object[]) al.toArray(new Object[al.size()]);
JOptionPane.showConfirmDialog(ui, obj);
I tried to implements programmatic panelmenu using defaultmenumodel and panelmenu with PrimeFaces 4.0. The problem is when I implement a simple model, one or more submenus that contains one o more menuitems runs ok. But when I implement submenus that contains menuitmes and more submenus that containts another menuitems, the defaultmenumodel not shows all levels.
Menu level one
...MenuItem one.one *
...MenuItem one.two *
...SubMenu one.one
......MenuItem one.one.one
......MenuItem one.one.two
...SubMenu one.two
......MenuItem one.two.one
Menu lebel two
... And so on
The MenuItem with * not shown when page is rendered
How can I implement these model of menu using DefaultMenuModel and ??
I want to use pojo to save the menu structure in DataBase for managing.
Thanks
(Added / Edited)
I have run next code suggested but not work using p:panelMenu. With p:menuBAr works well showing an Item and a SubMenu with item inside.
//create the first menu item It is not SubMenu, It's a simple MenuItem
//This item not shows in <p:panelmenu>
DefaultMenuItem accueil = new DefaultMenuItem();
accueil.setStyleClass("only simple menuItem");
accueil.setUrl("/accueil.jsf");
this.menumodel.addElement(accueil);
//This work properly ans shows in <p:panelMenu>
DefaultSubMenu submenu = new DefaultSubMenu();
submenu.setIcon(null);
submenu.setLabel("submenu 01");
this.menumodel.addElement(submenu);
//Add items to submenu
DefaultMenuItem item = new DefaultMenuItem();
item.setValue("Administrar Usuarios");
item.setUrl("/clientapp/modules/admin/manage_users.xhtml");
submenu.addElement(item);
I create my menu like this :
Bean:
private MenuModel menumodel = new DefaultMenuModel();
//create the first menu item
DefaultMenuItem accueil = new DefaultMenuItem("Accueil");
accueil.setStyleClass("accueil");
accueil.setUrl("/accueil.jsf");
this.menumodel.addElement(accueil);
//Start here i create submenu with personal access for all user
for (Autorisation auto : this.permList) {
if (auto.getRessource().getSousMenu() != null) {
if (auto.getRessource().getSousMenu().size() != 0) {
//Create submenu
DefaultSubMenu submenu = new DefaultSubMenu();
submenu.setIcon(null);
submenu.setLabel(auto.getRessource().getMenu());
this.menumodel.addElement(submenu);
for (Ressource r : auto.getRessource().getSousMenu()) {
//Feed submenu with menu item
DefaultMenuItem item = new DefaultMenuItem();
item.setValue(r.getMenu());
item.setUrl(r.getPath());
submenu.addElement(item);
}
}
}
}
XHTML :
<p:menubar model="#{SessionUser.menumodel}"/>
I respond myself.
To use menumodel you need a submenu that wraps (or contains) all menuitems or submenus with their own menuitems.
Create Menumodel.
Create Submenu mySubmenu.
Create one or more Menuitems and then add them to mySubmenu.
Create one or more Submenu objects (that can contains Menuitems
itself) an add to mySubMenu.
finally add mySubmenu that contains all MenuItem and Submenu items to
Menumodel that created initially.
Thanks Lamq, you help me to active my main. (And sorry for my english ::)
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);