In my project I have a table. When the user double clicks on the row, an editing dialog opens. On the opening this dialog I set values to fields, few of which are ChoiceBoxes. The type of ChoiceBox's field is a custom object, not a string.
The code that creates the ChoiceBox follows:
trade_point.setConverter(new TradePointConverter());
trade_point.setItems(FXCollections.observableArrayList(tradePointsService.getTradePoints()));
TradePoint currentTradePoint = tradePointsService.getTradePoint(typeOfPriceByTradePoint.getTradePoint());
trade_point.setValue(currentTradePoint);
Where trade_point is a choice box of TradePoint type. currentTradePoint is not null, when I look at trade_point's value equals currentTradePoint's value but in the dialog I see no value. Items are set correctly. in other case with same choice box filling everything is correct and here is not.
UPD: TradePointConverter class:
class TradePointConverter extends StringConverter<TradePoint>{
public TradePoint fromString(String name){
try {
List<TradePoint> tradePoints = tradePointsService.getTradePoints();
for (TradePoint tradePoint1: tradePoints){
if (tradePoint1.getName().equals(name)){
return tradePoint1;
}
}
}catch (SQLException e){
}
return null;
}
public String toString(TradePoint tradePoint1){
return tradePoint1.getName();
}
}
I am not sure if this converter is correct as far as converting from string by name is totally incorrect. I do not understand how to make it correctly visible to the user (to see the name of an object) and how to store its id to get the definite object at the same time. I can convert to string by getting an id but in this case user won't understand which object to choose.
trade_point is a ChoiceBox:
private ChoiceBox<TradePoint> trade_point = new ChoiceBox<TradePoint>();
Related
I have a program GUI that the user enters ID#, First Name, Last Name, Salary, Start Date. After the user enters this information into a text area for each information need, the users clicks the add button which stores the information into an arrayList. After clicking add, the user presses a "list" button to output all the information entered into a Panel.
Array list to store users data:
public class EmploymentRecords extends javax.swing.JFrame {
ArrayList <Data> Output = new ArrayList <Data>();
Remove Button code:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
boolean idCheck = Output.contains(id);
if (idCheck = true){
index = Output.indexOf(id);
Output.remove(index);
lblError.setText("Employee found and has been removed.");
}
else {
lblError.setText("Employee not found. Please try again.");
}
class Data:
class Data {
String id, firstName, lastName, salary, startDate;
Data (String _id, String _firstName, String _lastName, String _salary, String _startDate) {
id = _id;
firstName = _firstName;
lastName = _lastName;
salary = _salary;
startDate = _startDate;
Heres my problem: I want the user to be able to enter an id in the text area of the GUI where the program checks if that ID is entered before and totally removes all the data from the output screen and arraylist using just the ID. The code I entered above is not working for me and when I press the remove button nothing happens.
Please help as i would appreciate this... Thanks!
You are missing some code to share. But lets suppose your "add" functionality is working.
Lets also suppose that "String id = txtID.getText();" will be able to get the id for you as a string.
An obvious mistake is "if (idCheck = true)", as in java you compare with "=="
So maybe you can try to fix it that way and report the answer.
What you have done works alright for single entity objects within an ArrayList (like ArrayList<String> or ArrayList<Integer> for example) but not so good for multi-entity objects like what you have in your Data class. In other words, each element within your ArrayList is holding an instance of a class and all members related to it, not just a simple String or an Integer.
You will need to go a wee bit deeper in order to actually acquire the ID of any particular Data object instance for comparison to what someone has supplied within a GUI, for example:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
String id = txtID.getText();
boolean found = false;
for (Data data : Output) {
if (data.id.equals(id) {
found = true;
Output.remove(data);
clearFieldsInForm();
break;
}
}
if (found) {
lblError.setText("Employee was successfully removed.");
}
else {
lblError.setText("Invalid ID! Employee not found! Please try again.");
}
}
You will notice the clearFieldsInForm(); method use in the above code. This method would just set all pertinent form fields to Null String ("") which is essentially nothing:
private void clearFieldsInForm() {
txtID.setText("");
txtFirstName.setText("");
txtLastName.setText("");
txtsalary.setText("");
txtStartDate.setText("");
}
I am building an editor application using GWT/GXT with gwt editor framework. For some cases I have to edit a list of dates. To do so I chose to use GridInlineEditing, it works fine, but I also have to make some format validation on my DateField inside the gridInlineEditing.
Basically, the default behavior of the editing is to "record" changes when CompleteEditEvent is fired regardless the result of the validation. I therefore tried to override the onCompleteEditHandler method like this (which obviously is the only way to do it according to GXT forum):
public class NameValueDTMEditorWidget extends GenericEditableListView<DTM, Date> implements Editor<NameValueDTM> {
private final static DTMProperties props = GWT.create(DTMProperties.class);
ListStoreEditor<DTM> values;
#Ignore
private DateField df = new DateField();
public NameValueDTMEditorWidget(String widgetTitle) {
super(widgetTitle, new ListStore<DTM>(props.key()), props.dtm());
DateTimeFormat dtf = DateTimeFormat.getFormat("yyyyMMddHHmmss");
df.setPropertyEditor(new DateTimePropertyEditor(dtf));
addEditorConfig(df); // parent class method basically doing: editing.addEditor(df), editing is GridInlineEditing
// Modifying grid cell render for a Date
Cell c = new DateCell(DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss"));
getColumnModel().getColumn(0).setCell(c);
values = new ListStoreEditor<DTM>(getStore());
editing.addCompleteEditHandler(new CompleteEditEvent.CompleteEditHandler<DTM>() {
#Override
public void onCompleteEdit(CompleteEditEvent<DTM> event) {
df.validate(); // I force field validation
if (df.getValue() == null || !df.isValid()) { // if value's not valid
getStore().clear(); // clear the store
DTM e = GWT.create(DTM.class);
getStore().add(e); // add a new value
editing.startEditing(event.getEditCell()); // start editing new value
df.forceInvalid(); // force invalid to get invilid display on the field
}
}
});
}
It does almost what I want, it stays in edition when value is not valid and everything, but when I input a valid value after a wrong one it knows the value is valid but it does not exit edition mode. I have also tried to do the samething keeping the wrong inputed value instead of clearing my store and creating a new value and it behaves exactly the same way, except that with this method I also have a display problem.
Does anybody know how to do this? I also have the same problem with a list of String.
Try using Converter
editing.addEditor(columnConfig, new Converter<String, Date>() {
#Override
public String convertFieldValue(Date date) { /* called when you leave the cell */
GridCell cell = (GridCell) editing.getActiveCell();
ListStore<DTM> store = grid.getStore();
DTM dtm = store.get(cell.getRow());
/*
* here you have the dtm object belongs to related cell and the date as input.
* done with your validation here.
*/
return dtf.format(date);
}
#Override
public Date convertModelValue(String date) { /* called when you focus in the cell */
return dtf.parse(date);
}
}, df);
Try calling Field#clearInvalid before validating the field (I think this would be done before the df.validate(); line in your example).
I have a JTable, and I want validate data in the first column. When the user type the entry in any cell in the first column and click in another cell (focus lost), I want show message that the entry is false, and focus again in the cell until the entry is valid.
First I thought that the cell is like the JTextFiled, so I have tried the method addFocusListener(...) but it doesn't work!
table.getValueAt(0, 0).addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
for (int n = 0; n <= table.getValueAt(0, 0).toString().length(); n++) {
if (Character.isDigit(table.getValueAt(0, 0).toString().charAt(n)) == false) {
JOptionPane.showMessageDialog(null,
"Error: code is a number !", "Error Message",
JOptionPane.ERROR_MESSAGE);
break;
} else
break;
}
}
}
}
});
creation of JTable:
String [][]data={ {"-","-","0","-"},
{"-","-","0","-"},
{"-","-","0","-"},
{"-","-","0","-"},
{"-","-","0","-"},
{"-","-","0","-"},
{"-","-","0","-"},
{"-","-","0","-"} };
String[] header = {"Code Projet", "Description", "Duree", "Taches anterieurs"};
table = new JTable(data, header);
The TableCellEditor that is added to a JTable will do any validation on the values that are entered into a JTable.
From the Java Table Tutorial:
The automatic checking of user-entered strings occurs when the default
editor attempts to create a new instance of the class associated with
the cell's column. The default editor creates this instance using a
constructor that takes a String as an argument. For example, in a
column whose cells have type Integer, when the user types in "123" the
default editor creates the corresponding Integer using code equivalent
to new Integer("123"). If the constructor throws an exception, the
cell's outline turns red and refuses to let focus move out of the
cell. If you implement a class used as a column data type, you can use
the default editor if your class supplies a constructor that takes a
single argument of type String.
So, if you want to just make sure the user enters in an Integer (which is what it looks like from your code), you can set the column type to a type of Integer .
table.setDefaultEditor(Integer.class,
new IntegerEditor(0, 100));
Now the DefaultCellEditor will do the checking for you, and throw an exception if the type is not correct. You will just have to make sure you catch the exception and deal with it properly.
I think tutorial I linked above on creating tables would be very helpful for you, especially the part I linked to which talks about validating user text.
I want to implement a Swing Input Dialog with different options shown in a combo box. My specific case is for Contact creation, the end user can choose between existing Contacts or create a new one himself.
So I've got this static method which basically returns a new instance of a JOptionPane, which has the available selection objects out of the box. Note this code creates, let's say the parent dialog, which offers selecting an existing contact or clicking on the button to create a new one:
/**
*
* #param message
* Here I've got a JPanel which allows the end user to show-hide
* the Contact creation dialog
* #param contacts
* Contact possibilities
* #return reference to the created JOptionPane
*/
public static JOptionPane newContactOptionPane(Object message,
Set<XmlContact> contacts) {
Object[] contactPossibilities = new Object[contacts.size()];
int index = 0;
for (XmlContact contct : contacts) {
contactPossibilities[index] = String.format("%s %s, %s",
contct.get_Surname1(), contct.get_Surname2(),
contct.get_Name());
index++;
}
JOptionPane optPane = new JOptionPane();
JOptionPane.showInputDialog(optPane, message, "Seleccionar Contacto",
JOptionPane.QUESTION_MESSAGE, null, contactPossibilities,
contactPossibilities[0]);
return optPane;
}
The invoker code would be something like:
JOptionPane contactSelectionPane =
ViewUtils.newContactOptionPane(createContactPanel, xmlContacts);
XmlContact selectedContact =
(XmlContact) contactSelectionPane.getValue();
Later on, I would like to recover the selected value using JOptionPane#getValue() method.
The desired behaviour is to show the form for Contact creation when clicking Crear nuevo contacto, so the previous JDialog will be hidden:
I've got two reasons for keeping the reference at the invoker code, the first one is because I would like to wrap the option pane to make it return an XmlContact object instead of an String and having to search it again the possible options once and again in my invoker code. The other one is because I want to keep a reference of contactSelectionPane for enabling a button into createContactPanel to show/hide it.
Now the contactSelectionPane.getValue() is obviously returning an String, which forces me to check the options again. How can I implement that?
Why don't you do something like this:
public class Option<X> {
private final X value;
private final String name;
public String toString() {
return name;
}
public X getValue() {
return value;
}
public Option(X value, String name) {
this.value=value;
this.name=name;
}
}
public static JOptionPane newContactOptionPane(Object message,
Set<XmlContact> contacts) {
Object[] contactPossibilities = new Object[contacts.size()];
int index = 0;
for (XmlContact contct : contacts) {
contactPossibilities[index] = new Option<XmlContact>(contct, String.format("%s %s, %s",
contct.get_Surname1(), contct.get_Surname2(),
contct.get_Name()));
index++;
}
JOptionPane optPane = new JOptionPane();
JOptionPane.showInputDialog(optPane, message, "Seleccionar Contacto",
JOptionPane.QUESTION_MESSAGE, null, contactPossibilities,
contactPossibilities[0]);
return optPane;
}
And later you do:
JOptionPane contactSelectionPane =
ViewUtils.newContactOptionPane(createContactPanel, xmlContacts);
XmlContact selectedContact =
((Option<XmlContact>) contactSelectionPane.getValue()).getValue();
Hope that helps.
EDIT:
as for creating a new XmlContact I'd simply add an additional Option to the list of available options similar to new Option<XmlContact>(new XmlContact(...), "Create new contact...");.
I would use a SelectionChangedListener in order to get the actual selected item from the JComboBox.
In order to get the new XmlContact if created I would use some kind of variable to remember the created XmlContact.
At last I would derive a new Class from JOptionPane in which I override the getValue method where I either get the new XmlContact or the selected one from the JComboBox. You then use this class rather than the pure JOptionPane.
I'm using the following
org.eclipse.jface.viewers.CheckboxCellEditor.CheckboxCellEditor(Composite parent)
I'm creating a table viewer with cellEditors and doing the following
CellEditor[] editors = new CellEditor[columnNames.length];
editors[7] = new CheckboxCellEditor(table);
I have a CellModifier that has the following
public Object getValue(Object element, String property) {
Object result = null;
...
result = Boolean.valueOf(task.isDfRequested());
return result;
}
public void modify(Object element, String property, Object value) {
item.isSelected(((Boolean)value).booleanValue());
}
Finally I have a LabelProvider that has the following
public String getColumnText(Object element, int columnIndex) {
String result = "";
try {
result = Boolean.toString(item.isSelected());
} catch (Exception ex) { }
break;
However, in my UI instead of having a check box I have the word true or false && clicking it results in switching state to false or true. Any ideas on why I don't have a checkbox??
I've searched in the source code of CheckboxCellEditor class and in the constructor the control associated to the CellEditor is created in the createControl(Composite parent) method. This method is abstract in CellEditor class and it's implemented like this in CheckboxCellEditor:
protected Control createControl(Composite parent) {
return null;
}
So a control is not created, that's why you don't see the checkbox. In the documentation of the Class you can read:
Note that this implementation simply
fakes it and does does not create any
new controls. The mere activation of
this editor means that the value of
the check box is being toggled by the
end users; the listener method
applyEditorValue is immediately called
to signal the change.
I solved this using a ComboBoxCellEditor with yes and no items.
Regards.
Well, I have no idea how SWT works or what component you are even talking about.
But I do know that when using Swing you can have custom editors for a column in a JTable. If you don't tell the table the class of data for the column then the toString() method of the data is invoked. But if you tell the table that Boolean data is displayed in the column then the table will use the check box editor.
Sounds like a similiar symptom, but I don't know your particular solution.
What I've decided to do is to just implement a dirty hack others have been using.
Create two images of check boxes, one checked the other not checked. Switch the state between the two based on the boolean.
It's not perfect, but for now it gets the job done