Put and Get Selected Radio Button from Radio Group using SharedPreferences - android-fragments

want to store selected radio from and radio group and once that fragment is again launch , previous selected radio should be selected , I tried but not able to get it .
I need to store selected position on Click of button only .
This is code which I am using :
radiogender=(RadioGroup)rootView.findViewById(R.id.radioGroup1);
radiogender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.radioButton1) {
Toast.makeText(getActivity(), "You: Dude !!!",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.radioButton2) {
Toast.makeText(getActivity(), "You: Babe !!!",
Toast.LENGTH_SHORT).show();
}
}
});

Try something like this
radiogender=(RadioGroup)rootView.findViewById(R.id.radioGroup1);
radioButton1=(RadioButton) rootView.findViewById(R.id.radioButton1);
radioButton2=(RadioButton) rootView.findViewById(R.id.radioButton2);
SharedPreferences myPrefs=context.getSharedPreferences("general",context.MODE_PRIVATE); //you can give any name in place of general to your preferences
radiogender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.radioButton1) {
Toast.makeText(getActivity(), "You: Dude !!!",
Toast.LENGTH_SHORT).show();
//save in preferences
myPrefs.edit().putInt("selected",1).commint();
} else if(checkedId == R.id.radioButton2) {
Toast.makeText(getActivity(), "You: Babe !!!",
Toast.LENGTH_SHORT).show();
//save in preferences
myPrefs.edit().putInt("selected",2).commit();
}
}
});
//check if there is any value in preferences and set accordingly
int s=myPrefs.getInt("selected",0); //will return 0 when nothing is stored
if(s==1){
radioButton1.setChecked(true);
} else if(s==2){
radioButton2.setChecked(true);
}
To add a value in preferences, you first use the edit() tag and then use putInt or putString ,etc. to add value to the preferences.
Example putInt("selected",1 ); Here the 'selected' is the key or name that you provide so that you can fetch the value with that key. And '1' is the value to be stored against that key.
Then use commit() to save the value in preferences.
When you need to fetch a value, you use getInt or getString etc. to fetch the value.
Example getInt("selected",0);. Here selected is the key whose value you want to fetch. 0 is the default value that will be supplied in case there is no value under the key that you have provided.
Hope this helps :)

Related

DatePicker selects selections even if binded property has not been set

I got my DatePicker. I check if new comming date is equal or greater than SelectedOrder.TargetDate.Date.
The check itself is fine and not allow if coindition is not match, nevertheless what user selects on calendar it stay in calendar. Why calendar sets user's selection even if SelectedTargetDate was not changed?
<DatePicker Date="{Binding SelectedTargetDate, Mode=TwoWay}"/>
public DateTime SelectedTargetDate
{
get => _selectedTargetDate;
set
{
if (SelectedOrder == null) return; //on program run first time it's null
if (value.Date < SelectedOrder.TargetDate.Date)
_pageService.DisplayAlert("Ostrzeżenie", "New date cannot be older than TargetDate", "ok", "cancel");
else
SetValue(ref _selectedTargetDate, value);
}
}
I don't know if I understand you correctly, do you want to keep the SelectedOrder.TargetDate if the condition is not satisfied ?
If yes,you could let your model implement INotifyPropertyChanged and change like below:
public class YourModel: INotifyPropertyChanged
{
...
public event PropertyChangedEventHandler PropertyChanged;
public DateTime SelectedTargetDate
{
get => _selectedTargetDate;
set
{
if (SelectedOrder == null) return; //on program run first time it's null
if (value.Date < SelectedOrder.Date)
{
_pageService.DisplayAlert("Ostrzeżenie", "New date cannot be older than TargetDate", "ok", "cancel");
}
else
{
_selectedTargetDate = value;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedTargetDate"));
}
}
}

Alert Message When TextField is empty (javafx)

I would like for my code to check if the textfields in my form are empty & then show a pop up alert message. My problem is, even if the textfields are filled in this alert message pops up as soon as I hit "ENTER" anyway. Any help is appreciated !
BtnEnter.setOnAction((ActionEvent e) -> {
if (txtfName.getText().isEmpty() | txtlName.getText().isEmpty() |
txtMI.getText().isEmpty() | txtStreeAdd.getText().isEmpty()
| txtCity.getText().isEmpty() | txtZip.getText().isEmpty()
| txtPhone.getText().isEmpty() | txtEmail.getText().isEmpty()
| txtSecEmail.getText().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Required Fields Empty");
alert.setContentText("The fields highlighted in red must be filled "
+ "out.\nPlease try again.");
alert.showAndWait();
I believe part of the issue may be using the single pipe | for OR instead of the standard ||.
However, there's another approach you could take that may be a little easier to read. This is how I handle validation in my applications:
public boolean validate() {
StringBuilder errors = new StringBuilder();
// Confirm mandatory fields are filled out
if (txtfName.getText().trim().isEmpty()) {
errors.append("- Please enter a first name.\n");
}
if (txtlName.getText().trim().isEmpty()) {
errors.append("- Please enter a last name.\n");
}
if (txtMI.getText().trim().isEmpty()) {
errors.append("- Please enter a middle initial.\n");
}
if (txtStreetAdd.getText().trim().isEmpty()) {
errors.append("- Please enter a street address.\n");
}
if (txtCity.getText().trim().isEmpty()) {
errors.append("- Please enter a city.\n");
}
if (txtZip.getText().trim().isEmpty()) {
errors.append("- Please enter a ZIP code.\n");
}
if (txtPhone.getText().trim().isEmpty()) {
errors.append("- Please enter a phone number.\n");
}
if (txtEmail.getText().trim().isEmpty()) {
errors.append("- Please enter a primary email address.\n");
}
if (txtSecEmail.getText().trim().isEmpty()) {
errors.append("- Please enter a secondary email address.\n");
}
// If any missing information is found, show the error messages and return false
if (errors.length() > 0) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Required Fields Empty");
alert.setContentText(errors.toString());
alert.showAndWait();
return false;
}
// No errors
return true;
}
This has the added benefit of letting the user know exactly what information is missing as well. With this, you simply call the validate() method when the user clicks the action button. If validate() comes back true, you know you have all the information needed.
You can also approach it in this another way without Alert alert = new Alert(Alert.AlertType.WARNING); Here is a piece of code:
public boolean validateForm() {
StringBuilder errors = new StringBuilder();
// Confirm mandatory fields are filled out
if (jTextField1.getText().trim().isEmpty()) {
errors.append("- Please enter a first name.\n");
jTextField1.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
if (jTextField2.getText().trim().isEmpty()) {
errors.append("- Please enter a last name.\n");
jTextField2.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
String s = ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
if (s.equals("")) {
errors.append("- Please choose a date.\n");
jDateChooser1.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
if (jTextField3.getText().trim().isEmpty()) {
errors.append("- Please enter the age.\n");
jTextField3.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
In this way, you can check if users know what exactly missing and show them an alert message. Add a listener for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(validateForm()) {
System.out.println("First name: "+jTextField1.getText());
System.out.println("Last name: "+jTextField2.getText());
System.out.println("Date: "+jDateChooser1.getDate());
System.out.println("Age: "+jTextField3.getText());
}
}

Combobox selections disappear when table editing canceled

Ok, I'm starting to lose my mind on this one. I have a tableview where there are 3 combobox table cells. The first is a box where a user can select a job, the job selected changes the next combobox's options (job category). The job category selection changes the options in the labor box. So the flow down is:
job > job category > labor.
I have a very peculiar problem. When editing the table, you can click on any box to get a corresponding list of the available selections based on the other fields. This works fine. Where it blows up is when a selection ISN'T made. To make things more interesting, it only effects the job and job category comboboxes the labor box works flawlessly.
symptom:
-- job category selection disappears when edit is canceled via esc or focus lost
-- selection chosen in the job category field is placed into the job field when editing is canceled via esc or upon loss of focus
Here's the steps to recreate the symptoms:
1) click on job category box and enable editing mode
2) make a new selection from the drop down list
new selection made img
3) click on the job box and enable editing
4) click off the job box and cancel editing by click on job category or labor box in the same row
5) enable job category editing and then cancel job category edit by clicking on either labor / labor boxes or using esc
lose the job category / job selections img
here is the code to initialize the graphic when it comes up:
public void initialize(URL location, ResourceBundle resources) {
/* this is here because the screen handler will load up the Main screen in the
in the hashmap; no connection data will be assigned to the user at that time.
Without this block, when the hashmap attempts to load the Main data this
will cause the screenhandler to error and the main application
to not load correctly. The block below initiatializes the connection to
prevent this from happening.*/
if ( vUsers.getConn() == null){
try {
//establishes a user's connection to the database
vUsers.ConnecrDB();
} catch (SQLException | IOException ex) {
//debugging catch
System.out.println(ex);
}
}
//set the job box list for the user
cmbxJobT.setItems(cmbxPopulator.getJobComboBox());
cmbxJobT.valueProperty().addListener(new ChangeListener<String>(){
#Override
//reads the user's selectino and returns the appropriate labor codes for the Employee
public void changed(ObservableValue o, String oldValue, String newValue){
if (newValue != null){
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(newValue));
}else {
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().add(null);
}
}
});
cmbxJobCatT.valueProperty().addListener(new ChangeListener<String>(){
#Override
//reads the user's selectino and returns the appropriate labor codes for the Employee
public void changed(ObservableValue o, String oldValue, String newValue){
if (newValue != null){
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(newValue));
}else {
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().add(null);
}
}
});
tblviewTime.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSel) ->{
if (newSel != null){
Model_Time current = tblviewTime.getSelectionModel().getSelectedItem();
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(current.getJob()));
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(current.getJobCat()));
}
if (newSel == null){
Model_Time current = tblviewTime.getSelectionModel().getSelectedItem();
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(current.getJob()));
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(current.getJobCat()));
}
});
addDragListeners(bertaTabPane);
}
here's the code that sets up the tableview:
public void btnTimeSearch(ActionEvent event){
//makes an instance of the toolkit needed to query user time.
Database_RetrievesTime userData = new Database_RetrievesTime();
//grabs data from the userinput fields to set the toolkit
userData.setDateSelect(lblPickDateT.getValue());
userData.setJobBoxSelect(jobTbl.getIdByDesc(cmbxJobT.getValue()));
userData.setLaborBoxSelect(laborTbl.getIdByDesc(cmbxLaborT.getValue()));
userData.setJobCatSelect(jobCatTbl.getIdByDesc(cmbxJobCatT.getValue()));
/*creates cell factories in each column and maps the cell values to the
observable array list's IDs. The section also sets the columns up for user
editing to be available and the methods to execute upon an editted cell
being committed to entry.
**NOTE: The values are retrieved by the model class's getter methods.
Changing a name in the model class requires the user to update the getters.
Naming convention does apply. So for example: a variable
named cscHelp is added, it would need to have a getter called getCscHelp otherwise
the corresponding column will return blanks.*/
//setup ID column
IDcol.setCellValueFactory(new PropertyValueFactory<>("ID"));
//setup Datecol
Datecol.setCellValueFactory(new PropertyValueFactory<>("userDate"));
Datecol.setCellFactory(DatePickerTableCell.forTableColumn());
//created a custom datepicker callback that can be reused throughout the code's interfaces
Datecol.setOnEditCommit((CellEditEvent<Model_Time,LocalDate> t) -> {
//generate a temporary variable to convert the LocalDate returned into a SimpleObjectProperty
ObjectProperty<LocalDate> temp = new SimpleObjectProperty(t.getNewValue());
//store the new value to the object's model
t.getRowValue().setUserDate(temp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
//signaling to the program that a change had been made
isChanged = true;
});
//job column setup
Jobcol.setCellValueFactory(new PropertyValueFactory<>("Job"));
Jobcol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getJobComboBox()));
/*creates a combobox filled with the populated items found at initialization of the screen
user inputs are automatically commited
*/
Jobcol.setOnEditCommit((CellEditEvent<Model_Time,String> t) -> {
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
//store selection to the object's model (unprocessed so values will show something like '6002: Kobota'
t.getRowValue().setJob(ssp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
cmbxJobCatT.getItems().clear();
cmbxJobCatT.getItems().addAll(cmbxPopulator.getJobCatComboBox(t.getRowValue().getJob()));
//signaling a change has been made
isChanged = true;
});
jobCatCol.setCellValueFactory(new PropertyValueFactory<>("JobCat"));
jobCatCol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getJobCatComboBox(cmbxJobT.getValue())));
jobCatCol.setOnEditCommit((CellEditEvent<Model_Time,String> t)->{
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
//store selection to the object's model (unprocessed so values will show something like '6002: Kobota'
t.getRowValue().setJob(ssp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
cmbxLaborT.getItems().clear();
cmbxLaborT.getItems().addAll(cmbxPopulator.getLaborComboBox(t.getRowValue().getJob()));
//signaling a change has been made
isChanged = true;
});
//labor column setup works just like the job column
Laborcol.setCellValueFactory(new PropertyValueFactory<>("Labor"));
Laborcol.setCellFactory(ComboBoxTableCell.forTableColumn(cmbxPopulator.getLaborComboBox(cmbxJobCatT.getValue())));
Laborcol.setOnEditCommit((CellEditEvent<Model_Time,String> t) -> {
SimpleStringProperty ssp = new SimpleStringProperty(t.getNewValue());
t.getRowValue().setLabor(ssp);
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
t.getTableView().getItems().get(t.getTablePosition().getRow()).setLabor(ssp);
isChanged = true;
});
//time column setup.
Timecol.setCellValueFactory(new PropertyValueFactory<>("Time"));
Timecol.setCellFactory(TextFieldTableCell.<Model_Time, Float>forTableColumn(new FloatStringConverter()));
Timecol.setOnEditCommit((CellEditEvent<Model_Time,Float> t) -> {
//temp variable initialiation
float token = t.getNewValue();
//generate a temporary variable to convert the float return to a SimpleFloatProperty
SimpleFloatProperty temp = new SimpleFloatProperty(token);
//now update the row's object
t.getRowValue().setTime(temp);
//store row's object to the change list
Helper_TimShArrGen.addToEditedMatrix(t.getRowValue());
isChanged = true;
});
//set tableView editable
tblviewTime.setEditable(true);
//sets tableView to allow multiline selection
TableViewSelectionModel<Model_Time> tvt = tblviewTime.getSelectionModel();
tvt.setSelectionMode(SelectionMode.MULTIPLE);
/* checks if edits have been made. If there are edits, it commits to the
database before wiping the arraylists and updating the table*/
if (isChanged == true){
/*makes sure there are no duplicate entries in the arraylist. Throws out
previous edits and takes the most recent*/
Helper_TimShArrGen.validateMatrixEntries();
//commits changes and resets the "isChanged" value.
isChanged = Helper_TimShArrGen.confirmChanges(vUsers, jobTbl, jobCatTbl, laborTbl, isChanged);
}
/*tells the kit to run the querytime Method which uses the user input data
and user data to search the timesheet tables and returns the user's time.*/
if (isChanged == false){
try {
rs = userData.queryTime(vUsers.getConn(), vUsers.getLogin_ID());
} catch (SQLException ex) {
System.out.println(ex);
}
} else {
return;
}
//sets up the observablelist for the tableview
renderTable.setTableView(tblviewTime);
ObservableList n = renderTable.generateTable(jobTbl, jobCatTbl, laborTbl, rs, vUsers.getConn());
//renders the data on the screen`
tblviewTime.setItems(n);
Helper_TimeBreakDown breakdown = new Helper_TimeBreakDown();
breakdown.setTblArr(n);
breakdown.BreakDwnTim();
lblMonTim.setText(String.valueOf(breakdown.getMon()));
lblTuesTim.setText(String.valueOf(breakdown.getTues()));
lblWedsTim.setText(String.valueOf(breakdown.getWeds()));
lblThursTim.setText(String.valueOf(breakdown.getThurs()));
lblFriTim.setText(String.valueOf(breakdown.getFri()));
lblSatTim.setText(String.valueOf(breakdown.getSat()));
lblSunTim.setText(String.valueOf(breakdown.getSun()));
lblWkTim.setText(String.valueOf(breakdown.getWeek()));
}
this is the segment from the class that handles the data that goes into the lists.
public ObservableList<String> getJobComboBox(){
//clear the jobList to clean out junk data between calls
jobList.clear();
//looks at the job table to determine if the job is active. If active, it reads the entry
for (count=0; count<= jobTbl.getTblArray().size()-1; count++){
if(jobTbl.getTblArray().get(count).isActive()){
/*here we scroll through the JobIDList and match the IDs to the jobtbl
data. When a match is hit, we grab up the number on the job and the description
this is added to another array that will become the combobox's list
*/
for(inCount = 0; inCount <= jobIDList.size()-1; inCount++){
if(jobIDList.get(inCount).getCol2ID() == jobTbl.getTblArray().get(count).getID()){
jobList.add(jobTbl.getNumById(jobIDList.get(inCount).getCol2ID())
+ ": " + jobTbl.getDescById(jobIDList.get(inCount).getCol2ID()));
}
}
}
}
/* there's probably a better dataset to use that won't allow duplicates
due to my lack of knowledge at this time, I elected to create a hashset, pass the arrayList
to the hashset to wipe out duplicates, and then pass it back to the arrayList to be used in the combobox
*/
Set<String> tmp = new HashSet();
tmp.addAll(jobList);
jobList.clear();
jobList.addAll(tmp);
jobList.add(null);
return jobList;
}
/**
*
* #param job Argument for the selected Job String
* #return returns the ObservableList of strings for the Job Category ComboBox
*/
public ObservableList<String> getJobCatComboBox(String job){
//clearing out old artifact data from the previous selection
jobCatList.clear();
//splitting the user's string selection apart (number as string, description as string)
int jID=0;
if (job != null){
if (job.contains(": ")){
String[] tmp = job.split(": ");
job = tmp[1];
}
}
// here we comb the job Table for a matching description and vacuum up the associated ID number
for(count=0; count<=jobTbl.getTblArray().size()-1; count++){
if(jobTbl.getTblArray().get(count).getDesc().equals(job)){
jID = jobTbl.getTblArray().get(count).getID();
}
}
/*using that jobID number to examine the fKey in the category table.
once we match the JobID to the fKey ID in the jobCat table, we scoop up the
the job Category code and description to create a list for the combobox
*/
for (count=0; count<= jobCTbl.getTblArray().size()-1; count++){
for(inCount = 0; inCount <= jobCatIDList.size()-1; inCount++){
if(jobCatIDList.get(inCount).getID() == jobCTbl.getTblArray().get(count).getID()){
if(jobCTbl.getTblArray().get(count).getfKeyId() == jID){
jobCatList.add(jobCTbl.getNumById(jobCatIDList.get(inCount).getID())
+ ": " + jobCTbl.getDescById(jobCatIDList.get(inCount).getID()));
}
}
}
}
//same house keeping to remove duplicates as described above
Set<String> tmp = new HashSet();
tmp.addAll(jobCatList);
jobCatList.clear();
jobCatList.addAll(tmp);
jobCatList.add(null);
return jobCatList;
}
/**
*
* #param jobCat Argument for the selected Job Category String
* #return ObservableList of strings for the Labor ComboBox
*/
public ObservableList<String> getLaborComboBox(String jobCat){
//temp arrays I needed to decode the affiliated connections
ArrayList<Integer> jCID = new ArrayList();
ArrayList<Integer> laborID = new ArrayList();
//house keeping to remove artifact data from previous selections
if(jCID != null){
jCID.clear();
}
if(laborID != null){
laborID.clear();
}
if(laborList !=null){
laborList.clear();
}
//split user's string selection for the job category (numerical code as sting, description as string)
if(jobCat != null){
if (jobCat.contains(": ")){
String[] tmp = jobCat.split(": ");
jobCat = tmp[1];
}
}
//use the description to find the affiliated job category ID
for(count=0; count<=jobCTbl.getTblArray().size()-1; count++){
if(jobCTbl.getTblArray().get(count).getDesc().equals(jobCat)){
jCID.add(jobCTbl.getTblArray().get(count).getID());
}
}
//use the job category ID to find the associated labor IDs from the associate entity table
for(count=0; count<=jCLTbl.getTblArray().size()-1; count++){
for(inCount=0; inCount<=jCID.size()-1; inCount++){
if(jCLTbl.getTblArray().get(count).getCol1ID() == jCID.get(inCount)){
laborID.add(jCLTbl.getTblArray().get(count).getCol2ID());
}
}
}
//use the labor ID to look up the needed data from the labor table.
for (count=0; count<= laborTbl.getTblArray().size()-1; count++){
for(inCount = 0; inCount <= laborID.size()-1; inCount++){
if(laborID.get(inCount) == laborTbl.getTblArray().get(count).getID()){
laborList.add(laborTbl.getNumById(laborID.get(inCount))
+ ": " + laborTbl.getDescById(laborID.get(inCount)));
}
}
}
//more housekeeping to remove duplicate entries.
Set<String> tmp = new HashSet();
tmp.addAll(laborList);
laborList.clear();
laborList.addAll(tmp);
laborList.add(null);
return laborList;
}
I know there are probably better ways to do things here. I'm still new to JAVA and coding. I work at a small company so I'm the only coder they employee. Unfortunately this limits me to what I can teach myself, so there are probably some more efficient ways to accomplish the same mission here. Anyway, if anyone could help me figure out what is going on, it would be appreciated.
The answer to this problem is actually found in the SetOnEdit portion of the jobcatCol.
upon closer inspection and a lot of debugging, I found that this line
t.getRowValue().setJob(ssp);
is actually supposed to be
t.getRowValue().setJobCat(ssp);
I also chose to forego the ComboBoxTableCell API and write my own combobox implementations for each cell. It's a very basic version found here:
public class JobComboBoxCell extends TableCell<Model_Time, String>
{
private ComboBox<String> comboBox;
private Helper_UserSpecificTimDat cmbxPopulator = new Helper_UserSpecificTimDat();
public JobComboBoxCell(Helper_UserSpecificTimDat cmbxPopulator)
{
comboBox = new ComboBox<>();
this.cmbxPopulator = cmbxPopulator;
}
#Override
public void startEdit()
{
if ( !isEmpty() )
{
super.startEdit();
comboBox.setItems( cmbxPopulator.getJobComboBox() );
comboBox.getSelectionModel().select( this.getItem() );
comboBox.focusedProperty().addListener( new ChangeListener<Boolean>()
{
#Override
public void changed( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue )
{
if ( !newValue )
{
commitEdit( comboBox.getSelectionModel().getSelectedItem() );
}
}
} );
setText( null );
setGraphic( comboBox );
}
}
#Override
public void cancelEdit()
{
super.cancelEdit();
setText( ( String ) this.getItem() );
setGraphic( null );
}
#Override
public void updateItem( String item, boolean empty )
{
super.updateItem( item, empty );
if ( empty )
{
setText( null );
setGraphic( null );
}
else
{
if ( isEditing() )
{
setText( null );
setGraphic( comboBox );
}
else
{
setText( this.getItem() );
setGraphic( null );
}
}
}
}
This code was courtesy of Uluk Biy's response in thread:Populate combo box list dynamically for each row in javaFx table view
I adapted his code a little bit to specifically fit my needs. This solved a problem with values disappearing from the job category field and from data transferring from the job category field to the Job field.
This was one of the harder pieces of code I've had to troubleshoot. It was a combination of how the ComboBoxTableCell operates, the dynamic data of my comboboxes, and a slip in the which setter I was calling. It was about a perfect storm of flubs that the program saw no exceptions for as a result.
Thank you for the help

Sitecore: Show input option after using menu context item

I've added a menu context item to the TreelistEx. This menu item sends a messages that I later catch in a HandleMessage method.
In this method i create a new item ( template type and parent item are given in the source of the treelist field ).
All i need now is a way to ask the user for a name. But i haven't been able to find a simple way to do this.
class MyTreeListEx : TreelistEx, IMessageHandler
{
void IMessageHandler.HandleMessage(Message message)
{
if (message == null)
{ return; }
if (message["id"] == null)
{ return; }
if (!message["id"].Equals(ID))
{ return; }
switch (message.Name)
{
case "treelist:edit":
// call default treelist code
case "mytreelistex:add":
// my own code to create a new item
}
}
}
Does anyone have any suggestions on how to achieve this ?
Edit: added image & code + i'm using Sitecore 8 Update 1
I don't know which version of Sitecore you use but what you can try is SheerResponse.Input method.
You can use it like this:
using Sitecore.Configuration;
using Sitecore.Globalization;
using Sitecore.Shell.Applications.ContentEditor.FieldTypes;
using Sitecore.Web.UI.Sheer;
void IMessageHandler.HandleMessage(Message message)
{
...
case "mytreelistex:add":
Sitecore.Context.ClientPage.Start(this, "AddItem");
break;
}
protected static void AddItem(ClientPipelineArgs args)
{
if (args.IsPostBack)
{
if (!args.HasResult)
return;
string newItemName = args.Result;
// create new item here
// if you need refresh the page:
//SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");
}
else
{
SheerResponse.Input("Enter the name of the new item:", "New Item Default Name", Settings.ItemNameValidation,
Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength);
args.WaitForPostBack();
}
}
This code will even validate your new item name for incorrect characters and length.

Delete JavaFX table row with delete key

Is there a way to delete selected table row using keyboard delete key?
Is there any example with this implementation?
Sure you can. You only have to register an EventHandler and listen to the specific KeyCode. Following example is for TreeTableView but should be applyable for all TableViews.
treeTableView.setOnKeyPressed( new EventHandler<KeyEvent>()
{
#Override
public void handle( final KeyEvent keyEvent )
{
final TreeItem<YourObject> selectedItem = treeTableView.getSelectionModel().getSelectedItem();
if ( selectedItem != null )
{
if ( keyEvent.getCode().equals( KeyCode.DELETE ) )
{
//Delete or whatever you like:
presenter.onEntityDeleteAction( selectedItem );
}
//... other keyevents
}
}
} );
After trying a lot I managed to intercept and handle (with my application logic) the Delete key (Del or Canc, as you prefer to call it).
Thanks to some debugging I understand that the Delete key is identified with the Unicode code: \u007F.
So, the moment I type the key, I read the character and compare it with this code.
Here is a piece of my code that has nothing to do with table views but I used it for a TextField.
The important thing is the reasoning.
#FXML
public void myKeyListener(KeyEvent keyEvent) {
//Matches and manage TAB, Enter and Delete buttons
if ((keyEvent.getCharacter().equals("\t") ||
keyEvent.getCharacter().equals("\r") ||
keyEvent.getCharacter().equals("\u007F") //<-- **THIS** is the important one! *****
)) {
//My / your application logic
keyEvent.consume(); //The documentation says: "Marks this Event as consumed. This stops its further propagation."
return;
}
//Other logic...
//Entered only to have test outputs
System.out.println("getCode: " + keyEvent.getCode());
System.out.println("getCharacter: " + keyEvent.getCharacter());
System.out.println("getText: " + keyEvent.getText());
System.out.println("isMetaDown: " + keyEvent.isMetaDown());
}
Outputs:
getCode: UNDEFINED
getCharacter: ⍰
getText:
isMetaDown: false
I hope it can be useful to someone else. 🤞
P.S. I'm using Windows 10 with italian keyboard layout. In case it's relevant.

Resources