I use in a JavaFX eclipse project FXGraphs. Now I wanna use a TableView. Therefore I wrote this Sample.fxgraph file (only tableview part):
TableView < Customer > {
columns : [
TableColumn < Customer, Integer > {
text : "Id",
PropertyValueFactory < Customer, Integer > {
cellValueFactory {
property : "id"
}
}
},
TableColumn < Customer, String > {
text : "Family name",
PropertyValueFactory < Customer, String > {
cellValueFactory {
property : "familyName"
}
}
}
]
}
Now the Sample.fxml file should be like this (only tableview part):
<TableView>
<columns>
<TableColumn text="Id">
<cellValueFactory>
<PropertyValueFactory property="id" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Family name">
<cellValueFactory>
<PropertyValueFactory property="familyName" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
Howerver there is an error "cellValueFactory cannot be resolved to a type." in the Sample.fxgraph file. Thats not an import problem. The program runs with the correct fxml-file. How can I fix it?
Thanks for reading.
This problem is solved by the comment from #fabian.
TableView < Customer > id tableView {
columns : [
TableColumn < Customer, Integer > id idTableColumn {
text : "Id",
cellValueFactory : PropertyValueFactory < Customer, Integer > {
property : "id"
}
},
TableColumn < Customer, String > {
text : "Family name",
cellValueFactory : PropertyValueFactory < Customer, String > {
property : "familyName"
}
}
]
}
Related
My problem is column row is not getting selected/highlighted on window when user presses any letter key on Keyboard.
I tried following code but when I use DataGridTextSearchBehaviour then SelectionChanged="DataGrid_SelectionChanged" is not working.
<DataGrid ItemsSource="{Binding DrugItems}" SelectedItem="{Binding SelectedDrugItem}"
SelectionChanged="DataGrid_SelectionChanged" Grid.Row="1" Grid.RowSpan="2" Grid.Column="0"
Grid.ColumnSpan="2" HorizontalScrollBarVisibility="Visible">
<i:Interaction.Behaviors>
<b:DataGridTextSearchBehavior />
</i:Interaction.Behaviors>
<DataGrid.Columns>
<DataGridTextColumn Header="{DynamicResource lang.ui.DrugName}" Binding="{Binding Brand_Name}" Width="Auto"
ElementStyle="{StaticResource verticalCenter}">
</DataGridTextColumn>
<DataGridTextColumn Header="{DynamicResource lang.ui.DoseForm}" Binding="{Binding Dose_Form}"
ElementStyle="{StaticResource verticalCenter}"/>
<DataGridTextColumn Header="{DynamicResource lang.ui.UOM}" Binding="{Binding UOM}"
ElementStyle="{StaticResource verticalCenter}"/>
</DataGrid.Columns>
</DataGrid>
I have created DataGridTextSearchBehavior this seperate class ,and if I set AssociatedObject.SelectionUnit = DataGridSelectionUnit.FullRow; then problem gets resolved but instead of selecting column full row gets selected which I dont need. I need to select/Highlight column wise data.
using System;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
namespace eIVFRes.Behaviors
{
public class DataGridTextSearchBehavior : Behavior<DataGrid>
{
private DataGridSelectionUnit _oldUnit;
public string TextPath
{
get => TextSearch.GetTextPath(AssociatedObject);
set => TextSearch.SetTextPath(AssociatedObject, value ?? string.Empty);
}
protected override void OnAttached()
{
// <Setter Property="IsTextSearchEnabled" Value="True" />
//<Setter Property="IsTextSearchCaseSensitive" Value="False" />
base.OnAttached();
AssociatedObject.IsTextSearchEnabled = true;
AssociatedObject.IsTextSearchCaseSensitive = false;
_oldUnit = AssociatedObject.SelectionUnit;
AssociatedObject.SelectionUnit = DataGridSelectionUnit.Cell;
AssociatedObject.SelectedCellsChanged += DataGrid_OnSelectedCellsChanged;
}
protected override void OnDetaching()
{
AssociatedObject.IsTextSearchEnabled = false;
AssociatedObject.SelectionUnit = _oldUnit;
AssociatedObject.SelectedCellsChanged -= DataGrid_OnSelectedCellsChanged;
base.OnDetaching();
}
private void DataGrid_OnSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{column row is not getting selected/highlighted on window when user presses any letter key on Keyboard.
if (!ReferenceEquals(sender, AssociatedObject))
return;
if (!AssociatedObject.SelectedCells.Any())
return;
var c = AssociatedObject.SelectedCells.First();
if (!(c.Column is DataGridTextColumn ct))
return;
var path = (ct.Binding as Binding)?.Path.Path ?? string.Empty;
if (string.IsNullOrWhiteSpace(path))
{
if (!string.IsNullOrWhiteSpace(TextPath))
{
TextPath = string.Empty;
TextSearch.SetText(AssociatedObject, string.Empty);
}
}
else
{
if (!path.Equals(TextPath, StringComparison.CurrentCulture))
{
TextPath = path;
TextSearch.SetText(AssociatedObject, string.Empty);
}
}
}
}
}
I feel this is weird. i can't get the Radio button to pre-select a saved value and it's driving me mad. I have this xaml:
<StackLayout Orientation="Horizontal" RadioButtonGroup.GroupName="Parities"
RadioButtonGroup.SelectedValue="{Binding Parity}">
<RadioButton Value="1" Content="Income" />
<RadioButton Value="-1" Content="Expense" />
<RadioButton Value="0" Content="Neutral" />
</StackLayout>
Furthermore, even if I replace SelectedValue with a hard coded literal value "1" (for Income), the radio button still show up blank. The only way that works is by setting IsChecked on each of the 3 options to have the them pre-selected.
What am I missing?
Based on your code ,I created a simple demo, but I couldn't reproduce this problem. It just works properly.
You can refer to the following code:
MyPage.xaml
<ContentPage.BindingContext>
<radiobuttondemos:MyViewModel></radiobuttondemos:MyViewModel>
</ContentPage.BindingContext>
<StackLayout>
<StackLayout Orientation="Horizontal" RadioButtonGroup.GroupName="{Binding GroupName}"
RadioButtonGroup.SelectedValue="{Binding Parity}">
<RadioButton Value="1" Content="Income" />
<RadioButton Value="-1" Content="Expense" />
<RadioButton Value="0" Content="Neutral" />
</StackLayout>
</StackLayout>
The MyViewModel.cs
public class MyViewModel : INotifyPropertyChanged
{
string groupName;
object parity;
public object Parity
{
get => parity;
set
{
parity = value;
OnPropertyChanged(nameof(Parity));
}
}
public MyViewModel () {
GroupName = "Parities";
Parity = "1";
}
public string GroupName
{
get => groupName;
set
{
groupName = value;
OnPropertyChanged(nameof(GroupName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Note:
In the constructor of MyViewModel, I initialize the value of variable Parity as follows:
Parity = "1";
And if we initialize a value as follows, the UI will not pre-select the saved value :
Parity = 1;
Working with a login control (username and password) I can press enter on the control and then tab (without entering anything) and I get the warning that says to enter a valid user name. This is the desired effect, however if I just tab or click out of the field the event does not trigger, nor does the cursor move to the next field if the user enters a username and just presses enter. Any suggestions?
Controller Code
void getUserName(ActionEvent event) {
userName.focusedProperty().addListener((ov, oldV, newV) -> {
if (!(userName.getText().isEmpty())) {
if (!newV) {
String textUserValue = userName.getText();
warningLabel.setVisible(false);
userPwd.requestFocus();
}
} else {
warningLabel.setText("Please enter a valid user name");
warningLabel.setVisible(true);
warningLabel.setStyle("-fx-text-fill: red; -fx-font-size: 12;");
userName.requestFocus();
}
});
}
#FXML
void pwdController(ActionEvent event) {
userPwd.focusedProperty().addListener((ov, oldV, newV) -> {
if (!newV) {
if (!(userPwd.getText().isEmpty())) {
String textPwdValue = userPwd.getText();
warningLabel.setVisible(false);
String uName = userName.getText();
ServiceWrapper.conn1(uName, textPwdValue);
srcUpi.setDisable(false);
tgtUpi.setDisable(false);
mrgEqstDt.setDisable(false);
userName.setDisable(true);
userPwd.setDisable(true);
srcUpi.requestFocus();
}
} else {
warningLabel.setText("Please enter a valid password");
warningLabel.setVisible(true);
warningLabel.setStyle("-fx-text-fill: red; -fx-font-size: 12;");
userPwd.requestFocus();
}
});
}
FXML Code
<TextField fx:id="userName" layoutX="15.0" layoutY="14.0" onAction="#getUserName" onMouseReleased="#getUserName" promptText="User Name" />
<Label layoutX="15.0" layoutY="42.0" text="User Name" />
<TextField fx:id="userPwd" layoutX="15.0" layoutY="72.0" nAction="#pwdController" promptText="Password" />
<Label layoutX="15.0" layoutY="100.0" text="Password" />
<Label fx:id="warningLabel" focusTraversable="false" layoutX="15.0" layoutY="138.0" prefHeight="18.0" prefWidth="170.0" text="securitywarning" visible="false" />
<Separator layoutY="168.0" prefHeight="7.0" prefWidth="200.0" />
This question already has answers here:
Javafx PropertyValueFactory not populating Tableview
(2 answers)
Closed 6 years ago.
I just started with javafx and I wanted to create a TableView with 3 columns where I can display some values.
I created the TableView and the columns with the scene editor as fxml file.
Then I created a class named Values with the special properties I matched to the columns where they should fit in.
Finally I set the observable list with the "Value" objects in it as items of the table. When I start the application, it only shows me an empty table.
I looked like 4 hours in the internet now and still not found an answer why this is not working for me.
Here my code:
Value Class:
public class Values {
public SimpleDoubleProperty PSI = new SimpleDoubleProperty(0);
public SimpleDoubleProperty ALPHA = new SimpleDoubleProperty(0);
public SimpleDoubleProperty DELTA = new SimpleDoubleProperty(0);
public Values(Double _PSI, Double _ALPHA, Double _DELTA) {
setPSI(_PSI);
setALPHA(_ALPHA);
setDELTA(_DELTA);
}
private void setPSI(Double p){
PSI.set(p);
}
private void setALPHA(Double p){
ALPHA.set(p);
}
private void setDELTA(Double p){
DELTA.set(p);
}
}
Controller:
#FXML Label psi;
#FXML Label alpha;
#FXML Label delta;
#FXML TextField betafield;
#FXML TextField lambdafield;
#FXML TextField lambdasatfield;
#FXML TableView<Values> table;
#FXML ObservableList<Values> oblist;
#FXML TableColumn <Values,Double> psicolumn;
#FXML TableColumn <Values,Double> alphacolumn;
#FXML TableColumn <Values,Double> deltacolumn;
#Override
public void initialize(URL location, ResourceBundle resources) {
psicolumn.setCellValueFactory(new PropertyValueFactory<Values, Double>("PSI"));
alphacolumn.setCellValueFactory(new PropertyValueFactory<Values, Double>("ALPHA"));
deltacolumn.setCellValueFactory(new PropertyValueFactory<Values, Double>("DELTA"));
}
#FXML
protected void buttonpressed(){
try {
Calculation cal = new Calculation(Double.parseDouble(betafield.getText()), Double.parseDouble(lambdafield.getText()), Double.parseDouble(lambdasatfield.getText()));
alpha.setText("Alpha: " + " " + cal.calculateAlpha());
delta.setText("Delta:"+ " " + cal.calculateDelta());
psi.setText("Psi:"+ " " + cal.calculatePSI());
table.setItems(FXCollections.observableArrayList(cal.calculateEvaluaiontable()));
}catch (NullPointerException e){
e.printStackTrace();
}
}
And my FXML:
<Tab text="tab" fx:id="tabe">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<TableView layoutX="4.0" layoutY="4.0" prefHeight="192.0" prefWidth="370.0" fx:id="table">
<columns>
<TableColumn prefWidth="120.0" text="PSI" fx:id="psicolumn" />
<TableColumn prefWidth="120.0" text="ALPHA" fx:id="alphacolumn" />
<TableColumn prefWidth="120.0" text="DELTA" fx:id="deltacolumn" />
</columns>
</TableView>
</children>
</AnchorPane>
</content>
</Tab>
Thanks for your help!
Let <name> denote the constructor parameter of PropertyValueFactory and let <Name> denote the same String, but with an uppercase first letter.
PropertyValueFactory can get the value from one of the following sources:
The property getter, i.e. the a method SomeObservableValue <name>Property().
The getter method, i.e. the method SomeType get<Name>().
None of those exist in your Values class.
For the psicolumn to work, Values needs a DoubleProperty PSIProperty() method or a double getPSI() method. (Same issue with the other columns)
I am trying to bind a datagrid item to a combox, so that when the user selects the item in the datagrid the form displays the selected data for editing, however one of my items is a combobox using a dataprovider.
I would like the item selected in the datagrid to match the selected item in the combobox, this part is fine however if my datagrid item is null then I cannot get the combox to set the selected index to -1?
(the same happens if you use the CRUD wizard in Flex builder 3 for ColdFusion)
I am using the following code for my custom combobox:
<mx:ComboBox
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns="*"
creationComplete="componentInit()"
>
<mx:Script>
<![CDATA[
import mx.utils.ObjectUtil;
import mx.controls.Alert;
[Bindable]
public var valueField:String = "";
[Bindable]
public var labelFields:Array = [];
public function componentInit():void {
this.labelFunction = renderLabelFunction;
}
public function renderLabelFunction(item:Object):String {
var result:String = "";
if (labelFields.length == 0) {
if (labelField != null) {
return item[labelField];
} else {
return item.toString();
}
}
else {
for(var i:int=0; i < labelFields.length; i++) {
if (i > 0) {
result += " ";
}
result += item[labelFields[i]];
}
}
return result;
}
override public function set selectedItem(val:Object):void {
//Alert.show(valueField +":" +ObjectUtil.toString(val));
if( this.valueField != null) {
for(var i:int=0; i < this.dataProvider.source.length; i++) {
var item:Object = this.dataProvider.source[i];
if ( item[valueField]== val ) {
// if it matches, make it selected.
this.selectedIndex = i;
break;
}
}
} else {
this.selectedIndex = -1;
}
}
public function get selectedItemValue():Object {
if( this.valueField != null && selectedItem != null) {
return selectedItem[valueField];
} else {
return text;
}
}
]]>
</mx:Script>
</mx:ComboBox>
and the MXML part calling the combox is:-
<mx:DataGrid id="clientDatagrid" selectedIndex="1" visible="true"/>
<mx:Form height="305">
<mx:FormItem direction="horizontal" label="Surname" required="true" visible="true" width="100%" horizontalAlign="left">
<mx:TextInput enabled="true" id="Surname" text="{clientDatagrid.selectedItem.Surname}" width="100%" visible="true"/>
</mx:FormItem>
<mx:FormItem direction="horizontal" label="Forename" required="true" visible="true" width="100%" horizontalAlign="left">
<mx:TextInput enabled="true" id="Forename" text="{clientDatagrid.selectedItem.Forename}" width="100%" visible="true"/>
</mx:FormItem>
<components:BindableComboBoxa id="gender"
dataProvider="{genderData}"
valueField="Code"
labelField="Description"
/>
</mx:form>
Any help would be much appreciated.
Thank you.
In selectedItem setter, testing this.valueField for nullity is useless because you set it to "Code" in the mxml. Instead you should test if val is null.
So just replace
if( this.valueField != null)
with
if( val != null)
and then it should work.
try setting a prompt for the combobox like this:
<components:BindableComboBoxa id="gender"
dataProvider="{genderData}"
valueField="Code"
labelField="Description"
prompt="Please Select"
/>