Vaadin: I need to set the selected row, after I update table content.
I have a Comboboxbutton containing different customers.
Additionally I have two tables, the first shows main categories and the secound shows subcategories.
Initially, no customer is selected, Main categories are shown, no subcategory is shown.
When I click on a category (lets say product for example!), sub-category table appers and shows sub-categories.
When I change the customer now from empty to a specific customer, both tables are filtered, BUT: The product-selection is lost. I need to set the selection to the one selected before.
I get the table content as an sql-container object from antoher class.
mainCatTable = new Table();
...
mainCatTable.setContainerDataSource(source.getMainCats());
//My Checkboxbutton
Combobox custBox = new ComboBox();
//Get the customers from the Database
custBox.setContainerDataSource(source.getCustomers());
custBox.setItemCaptionPropertyId("Customers");
custBox.addValueChangeListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent valueEvent) {
//Here I need to store the old selection, before i update the mainCat table to a specific customer
mainCatTable.setContainerDataSource(source.getMainCats(currentCustomer));
//Here I need something to set the selected row to the previous value
subCatTable.setContainerDataSource(source.getSubCats());
}
});
The sql-container which the getMainCats method returns, is created like this:
FreeformQuery subcatExtractionQuery = new FreeformQuery("select customerName from customers", connectionPool);
return new SQLContainer(subcatExtractionQuery);
The problem is, t tried different ways, but it didn't work.
This was my try:
https://vaadin.com/forum/#!/thread/1819417/1819416
But they use an indexcontainer, but I don't.
Can anybody explain how to do this WITHOUT an index container?
What about to use value of the table to get/set "selected" row?
Object value = mainCatTable.getValue();
mainCatTable.setContainerDataSource(source.getMainCats(currentCustomer));
mainCatTable.setValue(value);
Related
I have an entity that has these two fields.
private boolean alarmActive;
private boolean messageHasBeenSent;
And when I show this with Vaadin CRUD API.
GridCrud<Alarm> alarmCrud = new GridCrud<>(Alarm.class);
CrudFormFactory<Alarm> crudFormFactory = new DefaultCrudFormFactory<Alarm>(Alarm.class);
alarmCrud.setCrudFormFactory(crudFormFactory);
alarmCrud.getGrid().setColumns("name", "email", "message", "alarmActive", "messageHasBeenSent", "sa0Min", "sa0Max", "sa1Min", "sa1Max", "sa1dMin", "sa1dMax", "sa2dMin", "sa2dMax", "sa3dMin", "sa3dMax", "a0Min", "a0Max", "a1Min", "a1Max", "a2Min", "a2Max", "a3Min", "a3Max");
alarmCrud.getGrid().setColumnReorderingAllowed(true);
crudFormFactory.setUseBeanValidation(true);
crudFormFactory.setVisibleProperties(new String[] { "name", "email", "message", "alarmActive", "messageHasBeenSent", "sa0Min", "sa0Max", "sa1Min", "sa1Max", "sa1dMin", "sa1dMax", "sa2dMin", "sa2dMax", "sa3dMin", "sa3dMax", "a0Min", "a0Max", "a1Min", "a1Max", "a2Min", "a2Max", "a3Min", "a3Max" });
I get this view when I try to add a new row in the CRUD database.
Question:
I want to have both check boxes on the same row? How can I do that with this current entity?
I know there is a way to have multiple check boxes at the same row, but that method is not the correct because it depends each checkbox need to become an entity and that entity is not connected to my database CRUD entity.
In this example below, he have used
#ManyToMany
#Fetch(FetchMode.JOIN)
#NotNull
private Set<Group> groups = new HashSet<>();
To create multiple check boxes at one row. The problem is that the entity Group is distinct from entity User if they begins with empty.
Here he loads the groupService into a check box provider and this creates multiple check boxes on the same row.
crud.getCrudFormFactory().setFieldProvider("groups", new CheckBoxGroupProvider<>("Groups", groupService.findAll(), Group::getName));
https://github.com/alejandro-du/crudui/blob/master/demo/src/main/java/org/vaadin/crudui/demo/ui/view/SimpleCrudView.java
I done it adding a component as column.
To do that, you need to remove from
alarmCrud.getGrid().setColumns(...)
the columns you want to group, and add them instead in a HorizontalLayout rendererd as column. Into HorizontalLayout you can add CheckBox, binding manually the values.
Perhaps there is a better solution, but one workaround is to add a line break after your Message field using JavaScript. This should have the effect of making both checkboxes in the same row.
To do this, you'd need to add an editor-opened listener in which you execute the following code to add the line break
com.vaadin.flow.component.UI.getCurrent().getPage()
.executeJs("formLayout = document.getElementsByTagName('vaadin-form-layout')[0];"
+ "var br = document.createElement('br');"
+ "formLayout.insertBefore(br, formLayout.children[3]);");
i am stuck with a new problem, don't know if this works but here i have list of JCombobox as follow.
JCombobox comboBox = new JComboBox();
comboBox.addItem("UserName");
comboBox.addItem("Password");
comboBox.addItem("DLNo 20 b");
comboBox.addItem("DLNo 20 b");
i want to print my database column names which are more than 40!
when i select the Combobox it must internally print my custom item here.
Here i tried with this code but i am not satisfied with this
if(comboBox.getSelectedIndex()==0)
{
System.out.println("U_NAME");
}
if(comboBox.getSelectedIndex()==1)
{
System.out.println("P_NAME");
}
if(comboBox.getSelectedIndex()==2)
{
System.out.println("DL_NO_20_b");
}
if(comboBox.getSelectedIndex()==3)
{
System.out.println("DL_NO_20_b");
}
is there any better way to over come this, like mapping objects
You could create a class ComboBoxItem with a name- and a columnName-attribute.
Use instances of this class for the ComboBox.
In the ComboBoxItem-class, overwrite the toString()-method to return the name, so it gets displayed as wished in the ComboBox. Add a getColumnName()-method to return the columnName, so you could invoke getSelectedItem().getColumnName().
I have a JTable which displays an Object[][] of data.
There is also a form on the same screen that lets the user add an item to the object to the list. Although for the life of me I can not get the list displayed in the table to update when the user presses the "Add Item" button.
(it gets appended to the array fine, and I can print it onto the screen, just can't get the table to change.)
Here is crating of the table
Object[] tableHeadings = {"Item Name","Qty/Weight","Price"};
ShoppingApplication shoppingApplication = new ShoppingApplication();
Object[][] tableData = shoppingApplication.generatePurchaseTableData();
final JTable tblBill = new JTable(tableData, tableHeadings);
Here is the table data being generated:
/**
* Generates data in the correct format to go into the table
* from the purchase list
* #return
*/
public Object[][] generatePurchaseTableData(){
Object[][] results = new Object[listOfPurchases.size()][2];
for (int i = 0; i<listOfPurchases.size(); i++){
Purchase purchase = listOfPurchases.get(i);
Object[] innerObject =
{purchase.getProductName(),
purchase.getPricePerUnit(),
purchase.getTotalPrice()};
results[i] = innerObject;
}
System.out.println(results.length);
return results;
}
}
Here's the action listener
/* Add Action Listeners */
cmdAddItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
AddPurchase addPurchase = new AddPurchase(
(radWeight.isSelected()) ? 'w' :(radQty.isSelected()) ? 'q' : 'u',
txtNameOfItem.getText(),
txtAmount.getText(),
txtUnits.getText(),
txtPricePerUnit.getText());
ShoppingApplication sa = new ShoppingApplication();
Object[][] newData = sa.generatePurchaseTableData();
//TODO make tblBill updata it's contents
}
});
From the code above, it does look like I haven't made much effort, but I've actually been trying to get this to work for hours now, tried using different methods, data structures and been getting no where to went right back to the start, and that is what the above code it.
I've Googled this a bit, and can't seem to find anything, can't think why no one else has seemed to get stuck on this. (maybe I'm just being thick) but hopefully this post will help others too.
Thanks in advance :)
The JTable has a data model (TableModel), which either holds the values, or is an adapter to the actual data.
Data in a table can be update by either changing the data in the table model, or by setting a new table model.
In your case, you could use the javax.swing.table.DefaultTableModel:
TableModel tableModel=new DefaultTableModel(newData, tableHeadings);
tblBill.setModel(tableModel);
update when the user presses the "Add Item" button.
Why do recreate the entire table when you only add a single item? That is not very efficient.
Instead must add a new row to the table. This code (like the above code) assumes you are using the DefaultTableModel:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(...);
I've created a database application with the NetBeans GUI-Designer.
GUI with Comboboxes (Bound to MySQL databasetables user and team):
on Button new -> jDialog - executes a query to store a new user in database:
Problem: Combobox is updated at the programstart but not while running the program.
Question: Is it possible to update the entries in my combobox directly when a new user or team is saved? And how could I Implement this?
Edit: Here is what I do when clicking on the saveButton in the JDialog:
int k=st.executeUpdate(
"INSERT INTO User (username) " + " VALUES ('"+ name + "')");
//Here I'd like to update the jComboBox1 directly if possible
Outerclass.jComboBox1...;
JOptionPane.showMessageDialog(null, "User is successfully saved");'
Just update your component's ComboBoxModel when you insert a new user in the database. If this is not helpful, please provide an sscce that exhibits the problem.
Addendum: Given a reference to a JComboBox,
private final JComboBox combo = new JComboBox();
you can update its model, as shown below. This example adds name to the beginning of the list, but SortedComboBoxModel is an appealing alternative.
DefaultComboBoxModel model = (DefaultComboBoxModel) combo.getModel();
model.insertElementAt(name, 0);
Addendum: More simply, use the method available to the combo itself,
combo.insertElementAt(name, 0);
I ran into a similar problem: if you enter anything into the database, that is supposed to be reflected in the JComboBox, then you can't change the values of that combo box. It would be great if you could add things to the JComboBox "on the fly" directly, but you have to get that data, create a new ComboBoxModel from it, and then set your JComboBox to that new model.
Here, I use DefaultComboBoxModel, which can either take an array of objects (usually strings) or a vector. If you use vectors to represent your underlying data model, that's a lot easier, since vectors are dynamic data structures.
My code:
Vector<String> s = new Vector<String>();
try {
// I'm using prepared statements, get the ResultSet however you like
ResultSet rs = myPreparedStatement.executeQuery();
while ( rs.next() ) {
// Change "1" to whatever column holds your data
s.add(rs.getString(1));
}
} catch (SQLException ex) {
ex.printStackTrace(); // or whatever
}
DefaultComboBoxModel jcbModel = new DefaultComboBoxModel(s);
jcb.setModel(jcbModel);
EDIT: Remember that ResultSet columns are 1-indexed, not 0-indexed! Gets me every time.
Requirement:
I have a list of strings displayed in the ComboBox. Each of these Strings can have some properties. These properties are displayed in PropertyTable. ComboBox's selected Item's properties are displayed in the table. In addition, we use PropertyTable for editing or setting property values to the selected item in the comboBox.
Problem:
The moment I de-select the comboBox Item,say item1, all the existing property values in the PropertyTable are set as new property values to item1. Again, when I select this item1 back, I should get above property values(i.e values before item1 is Deselected) back in to the PropertyTable?
Current Implementation Logic:
I am having TableCellListner for each PropertyTableCell, whenever cell content is changed, it takes the cell's new value and assigns this as new property value to the combo box's selected item. whenever new item is selected, table is refreshed with the selected Item's property values.
//before is Table initialization code
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
TableCellListener table = (TableCellListener)e.getSource();
String selectedItem=(String)ComponentPropComboBox.getSelectedItem();
if(table.getColumn()==1 && selectedItem!=null)
{
Property property=propertyMap.get(selectedItem);
else if(table.getRow()==0)
{
property.setProperty("MIN_LENGTH", (String)table.getNewValue());
propertyMap.put(selectedItem, property);
}
else if(table.getRow()==1)
{
property.setProperty("STARTS_WITH_STRING", (String)table.getNewValue());
propertyMap.put(selectedItem, property);
}
}
}
};
TableCellListener tcl = new TableCellListener(PropertiesTable, action);
How do i implement this requirement by overcoming the above challenge?
PS:
TableCellListner is a Not a java generic library. You can view code and its explanation at the following links:
http://www.camick.com/java/source/TableCellListener.java
http://tips4java.wordpress.com/2009/06/07/table-cell-listener/
I believe the question is obvious! Pls do let me know if question is not clear.Thanks in advance for your help & donating the knowledge!
In the code that listens for JComboBox selections. At its start have it set a boolean that the item is being changed. Then have your table refresh code ignore events that come while the boolean is set. After you are finished refreshing then set the boolean back.