Bit of an odd one, I'm using JavaFX 8 and am having some odd behaviour I picked up during my Jubula testing.
I have a datepicker control that is created with the following code:
public DatePicker getDatePicker(DtDate defaultDate, int width){
DatePicker dtpckr = new DatePicker();
dtpckr.setMaxWidth(width);
dtpckr.setMinWidth(width);
dtpckr.setConverter(new StringConverter<LocalDate>() {
private DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy/MM/dd");
#Override
public String toString(LocalDate localDate) {
if(localDate==null)
return "";
return dateTimeFormatter.format(localDate);
}
#Override
public LocalDate fromString(String dateString) {
if(dateString==null || dateString.trim().isEmpty())
return null;
return LocalDate.parse(dateString,dateTimeFormatter);
}
});
dtpckr.setPromptText("yyyy/MM/dd");
dtpckr.setValue(LocalDate.parse(defaultDate.toString(), DateTimeFormatter.ofPattern("yyyy/MM/dd")));
return dtpckr;
}
That works fine and the control is created on the form and works as expected. If I use the calendar to pick the date, the value is updated.
Now, for the odd part, if I enter in the datepicker and manually type the date in (E.g. 2017/10/11) and then exit the control by either tabbing or clicking on the next textbox on the form, the datepicker localdate value doesn't get updated. The only method to update the date would be to press enter to force the datepicker to realise a new value is present. This causes another problem as I have the following code:
public void createSetDateAndTimeControls(){
DtDateAndTime currentDateAndTime;
try {
currentDateAndTime = systemstateController.getServerDateTime();
/*
* Creating controls to be used on the form
*/
int width = 150;
DatePicker dtpckr = getDatePicker(currentDateAndTime.date, width);
Label lblDate = new Label("Date:");
Label lblTimeHour = new Label("Hour:");
Label lblTimeMinute = new Label("Minute:");
Label lblTimeSecond = new Label("Second:");
TextField txtfldCurrentSetSecond = new TextField();
TextField txtfldCurrentSetMinute = new TextField();
TextField txtfldCurrentSetHour = new TextField();
Slider sldrHourPicker = getSlider(width, SliderType.Hour, txtfldCurrentSetHour, currentDateAndTime.time);
Slider sldrMinutePicker = getSlider(width, SliderType.Minute, txtfldCurrentSetMinute, currentDateAndTime.time);
Slider sldrSecondPicker = getSlider(width, SliderType.Second, txtfldCurrentSetSecond, currentDateAndTime.time);
/*
* Adding a grid pane to keep controls in correct place and aligned correctly
*/
GridPane grdpn = new GridPane();
grdpn.add(lblDate, 1, 1);
grdpn.add(dtpckr, 2, 1, 2,1);
grdpn.add(lblTimeHour, 1, 2);
grdpn.add(sldrHourPicker, 2, 2, 2 ,1);
grdpn.add(txtfldCurrentSetHour, 4, 2);
grdpn.add(lblTimeMinute, 1, 3);
grdpn.add(sldrMinutePicker, 2, 3, 2, 1);
grdpn.add(txtfldCurrentSetMinute, 4, 3);
grdpn.add(lblTimeSecond, 1, 4);
grdpn.add(sldrSecondPicker, 2, 4, 2, 1);
grdpn.add(txtfldCurrentSetSecond, 4, 4);
/*
* Creating buttons for user to press
*/
Button bttnOK = new Button("Change date and time");
bttnOK.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
if (checkIfAllDialogHasBeenFilledIn(grdpn)){
LocalDate test = dtpckr.getValue();
if (systemstateController.oeSetClock(ICrashUtils.setDateAndTime(dtpckr.getValue().getYear(), dtpckr.getValue().getMonthValue(), dtpckr.getValue().getDayOfMonth(),
(int)Math.floor(sldrHourPicker.getValue()), (int)Math.floor(sldrMinutePicker.getValue()), (int)Math.floor(sldrSecondPicker.getValue()))).getValue())
showOKMessage("Updated", "Date and time was updated successfully");
else
showErrorMessage("Error", "There was an error updating the date and time");
}
else
showUserCancelledActionPopup();
} catch (ServerOfflineException | ServerNotBoundException e) {
showExceptionErrorMessage(e);
}
}
});
bttnOK.setDefaultButton(true);
grdpn.add(bttnOK, 2, 5, 3, 1);
Button bttnSetNow = new Button("Now");
bttnSetNow.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
dtpckr.setValue(LocalDate.now());
LocalTime time = LocalTime.now();
sldrHourPicker.setValue(time.getHour());
sldrMinutePicker.setValue(time.getMinute());
sldrSecondPicker.setValue(time.getSecond());
}
});
grdpn.add(bttnSetNow, 4, 1);
/*
* End of creating controls to be used on the form
*/
anchrpnActivator.getChildren().add(grdpn);
AnchorPane.setTopAnchor(grdpn, 0.0);
AnchorPane.setRightAnchor(grdpn, 0.0);
AnchorPane.setLeftAnchor(grdpn, 0.0);
AnchorPane.setBottomAnchor(grdpn, 0.0);
} catch (ServerOfflineException | ServerNotBoundException e) {
showExceptionErrorMessage(e);
}
}
Which has the following line:
bttnOK.setDefaultButton(true);
This means that if a user presses enter during the text entry on the date picker control, it fires off the onaction event, before the user has put in data in the other controls, and I don't particularly want that.
So the question is, why doesn't the dtpckr.getValue() change if a user enters text into the box and then leaves the box without pressing enter? I can't find an event to call on user leaving the datepicker box or a property of the datepicker to get the text value of the control and compare it to the value of dtpckr.getValue(). Is there something that I'm missing here?
Let me know if you need more information!
[Edit]
It appears this might be a bug in the current datepicker setup in JavaFX
I might have to remove the default button and put in an enter press in the Jubula test to make this work properly. Unless someone has an alternative?
The bug log that I added above had the answer. You can access the string value of the textbox via this code:
datePicker.getEditor().getText();
So setting the textbox value can be done via:
datePicker.setValue(datePicker.getConverter()
.fromString(datePicker.getEditor().getText()));
I'm adding an event to the lost focus event, that will force the datepicker value to be updated
And the working code:
public DatePicker getDatePicker(DtDate defaultDate, int width){
DatePicker dtpckr = new DatePicker();
dtpckr.setMaxWidth(width);
dtpckr.setMinWidth(width);
dtpckr.setConverter(new StringConverter<LocalDate>() {
private DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy/MM/dd");
#Override
public String toString(LocalDate localDate) {
if(localDate==null)
return "";
return dateTimeFormatter.format(localDate);
}
#Override
public LocalDate fromString(String dateString) {
if(dateString==null || dateString.trim().isEmpty())
return null;
try{
return LocalDate.parse(dateString,dateTimeFormatter);
}
catch(Exception e){
//Bad date value entered
return null;
}
}
});
dtpckr.setPromptText("yyyy/MM/dd");
dtpckr.setValue(LocalDate.parse(defaultDate.toString(), DateTimeFormatter.ofPattern("yyyy/MM/dd")));
//This deals with the bug located here where the datepicker value is not updated on focus lost
//https://bugs.openjdk.java.net/browse/JDK-8092295?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
dtpckr.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue){
dtpckr.setValue(dtpckr.getConverter().fromString(dtpckr.getEditor().getText()));
}
}
});
return dtpckr;
}
#Draken's answer needs a little extra. If the user types an invalid date the code will throw a DateTimeParseException. You can emulate the DatePicker's own behaviour thus:
dtpckr.getEditor().focusedProperty().addListener((obj, wasFocused, isFocused)->{
if (!isFocused) {
try {
dtpckr.setValue(dtpckr.getConverter().fromString(dtpckr.getEditor().getText()));
} catch (DateTimeParseException e) {
dtpckr.getEditor().setText(dtpckr.getConverter().toString(dtpckr.getValue()));
}
}
});
I recently fixed this issue in the newest JavaFX version: https://github.com/openjdk/jfx/pull/679
So when JavaFX 18-ea+9 will be released you can use it and remove the workaround. :-)
I had the same problem. Did this trick to solve it:
Date date = DateConverter.toDate(datePicker.getEditor().getText());
where DateConverter.toDate() is a method that converts the string to date.
I know it’s a little off topic, but for a while I had users who didn’t press ENTER to submit, so I did this.
/**
* This will automatically submit the input on lost of focus, if it's typed but not submitted (with ENTER).
*
* #param picker to apply
*/
private void activateAutoSubmit(DatePicker picker) {
// On Focus Leave Listener
picker.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
try {
// Set typed text to DatePicker value
picker.setValue(picker.getConverter().fromString(picker.getEditor().getText()));
} catch (Exception e) {
// For wrong input return old value
picker.getEditor().setText(picker.getConverter().toString(picker.getValue()));
}
}
});
}
Usage
#FXML
private DatePicker dateStart;
#FXML
private DatePicker dateEnd;
#FXML
private void initialize() {
...
activateAutoSubmit(dateStart);
activateAutoSubmit(dateEnd);
...
}
Related
hi i am newbie to blackberry.i will be having two buttons one for addition of rows and other for deletion of rows.
|--------------------------------------------|
||----------------------------------||------||
||labelfield ||Bitmap||
||__________________________________||______||
|____________________________________________|
|--------------------------------------------|
| Editfield |
|--------------------------------------------|
Above is customized view of datepicker,Where on click of bitmap datepicker popups to choose date and that date value get binded to edit field,this is contained in one row and other row contains an edit field which allows to enter amount which shall be formatted as user enter's numerals.
Initially two default row will be present to choose date and enter amount.On click of add button these two rows shall be added.and these rows values will be retrieved whenever required.
similarly on click of deletion button these two rows will get deleted.If user has to add next two rows the previous rows must be filled.
the code i have used for datepicker is given below
VerticalFieldManager datevertfield = new VerticalFieldManager();
String pattern = "MM/dd/yyyy";
String dateInString = new SimpleDateFormat(pattern).format(new Date());
LabelField lblcal1 = new LabelField("Date", DrawStyle.LEFT
| Field.FIELD_LEFT) {
public void paint(Graphics g) {
g.setColor(0xffffff);
super.paint(g);
}
};
datevertfield.add(lblcal1);
HorizontalFieldManager datepickerHoriztalField = new HorizontalFieldManager();
HorizontalFieldManager dateHoriztalField = new HorizontalFieldManager()
{
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth() - horiwidth, horiheight);
setExtent(Display.getWidth() - horiwidth, horiheight);
}
};
XYEdges xyEdge1 = new XYEdges(border, border, border, border);
XYEdges xyEdgeColors1 = new XYEdges(0x2AACFF, 0x2AACFF, 0x2AACFF,
0x2AACFF);
Border aBorder1 = BorderFactory.createSimpleBorder(xyEdge1,
xyEdgeColors1, Border.STYLE_SOLID);
dateHoriztalField.setBorder(aBorder1);
datepickerHoriztalField.add(dateHoriztalField);
BitmapField iconimg = new BitmapField(
GPATools.ResizeTransparentBitmap(
Bitmap.getBitmapResource("Calender.png"),
imgwidth, imgheight, Bitmap.FILTER_LANCZOS,
Bitmap.SCALE_TO_FIT), Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
try {
DateTimePicker datePicker = DateTimePicker.createInstance();
datePicker.doModal();
Calendar cal = datePicker.getDateTime();
datePicker.setMaximumDate(cal.getInstance());
Date curtime = cal.getTime();
DateFormat formattertime = new SimpleDateFormat(
"MM/dd/yyyy");
String currentTime = formattertime.format(curtime);
txtpickdate.setText(currentTime);
} catch (Exception e) {
}
return true;
}
};
txtpickdate = new LabelField("Enter Date", DrawStyle.LEFT
| Field.FIELD_LEFT) {
protected void paint(Graphics g) {
g.setColor(Color.WHITE);
super.paint(g);
}
};
dateHoriztalField.add(txtpickdate);
datepickerHoriztalField.add(iconimg);
datevertfield.add(datepickerHoriztalField);
add(datevertfield);
This is code used for date picker row like this i want to add datepiker row and next edit field row on click of butn .and this could be deleted on click of delete btn.
In this i need to know how to add and delete these rows and how to know whether user has entered previous Date and edit field row to do validation.
Could anyone give me idea on how to start with this.Code example will be appreciated.
I'm not sure if I understood the question or not, but from what I understand you are looking for:
A label & Button to select date
EditField restricted to numerical text
Button to create a field from a date and number
Created Fields can be deleted
I created a smallish example for doing this. I did not include the number restriction on the text field, but the rest should be a decent base to start from. I would recommend not using a BitmapField as a button because it won't be good for ux. You'll likely want a field with images for each state (none, focused, pressed)
public final class MyScreen extends MainScreen
{
private Calendar calendar;
private LabelField labelField;
private BitmapField bitmapField;
private EditField editField;
private SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
public MyScreen()
{
super(NO_HORIZONTAL_SCROLL);
// ----- TODO ------
// Too lazy to include a bmp, so I generated one. You should replace this with your icon
Bitmap bmp = new Bitmap(50, 50);
Graphics g = Graphics.create(bmp);
g.setColor(0xEFEFEF);
g.fillRect(0, 0, bmp.getWidth(), bmp.getHeight());
// ------------------
bitmapField = new BitmapField(bmp, FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
if (calendar == null)
{
calendar = Calendar.getInstance();
}
DateTimePicker datePicker = DateTimePicker.createInstance(calendar);
datePicker.doModal();
calendar = datePicker.getDateTime();
if (calendar == null)
{
labelField.setText("null"); // Your error message here
}
else
{
labelField.setText(formatter.format(calendar.getTime()));
}
return true;
}
};
labelField = new LabelField(null, USE_ALL_WIDTH) // Tell labelField to use as much width as possible
{
protected void layout(int width, int height)
{
// Layout the label as though less space is available (to fit the bitmap button in)
super.layout(width - bitmapField.getBitmapWidth(), height);
}
};
HorizontalFieldManager manager = new HorizontalFieldManager(USE_ALL_WIDTH);
add(manager);
manager.add(labelField);
manager.add(bitmapField);
editField = new EditField(USE_ALL_WIDTH);
add(editField);
ButtonField addButton = new ButtonField("ADD")
{
protected boolean navigationClick(int status, int time)
{
String text = editField.getText();
if ((calendar != null) && (text != null) && (text.length() > 0))
{
add(new EntryField(calendar.getTime(), text));
}
else
{
// TODO notify invalid data?
}
return true;
}
};
add(addButton);
}
public class EntryField extends HorizontalFieldManager
{
public EntryField(Date date, String text)
{
super(USE_ALL_WIDTH);
// ----- TODO ------
// Too lazy to include a bmp, so I generated one. You should replace this with your icon
Bitmap bmp = new Bitmap(50, 50);
Graphics g = Graphics.create(bmp);
g.setColor(0xFF0000);
g.fillRect(0, 0, bmp.getWidth(), bmp.getHeight());
// ------------------
final BitmapField bitmapField = new BitmapField(bmp, FOCUSABLE)
{
protected boolean navigationClick(int status, int time)
{
EntryField.this.getManager().delete(EntryField.this); // Remove this field from its parent
// Depending on what kind of interactions this field exposes, this will most likely need to make use of a callback instead.
return true;
}
};
final LabelField labelField = new LabelField(formatter.format(date) + " - " + text, USE_ALL_WIDTH) // Tell labelField to use as much width as possible
{
protected void layout(int width, int height)
{
// Layout the label as though less space is available (to fit the bitmap button in)
super.layout(width - bitmapField.getBitmapWidth(), height);
}
};
add(labelField);
add(bitmapField);
}
}
}
I've got a problem with a Java project I'm working on: I'm creating a grid of buttons via code in javafx on a pane. The buttons are all types of a subclass of the javafx Button class that i wrote.
Here's the header of the class:
private final String BASIC_STYLE = "-fx-font: 6 arial;";
private final String CLICKED_STYLE = "-fx-background-color: #0f0";
private int row;
private int col;
private String category;
private boolean selected = false;
Within the constructor i do the follwing:
this.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
toggleSelected();
}
});
Here's the toggleSelected() Method:
public void toggleSelected() {
this.selected = !selected;
this.setStyle(selected ? this.BASIC_STYLE : this.BASIC_STYLE+this.CLICKED_STYLE);
}
It's basically supposed to swap the style everytime you click the button. When i click the button, the button first gets selected by the OS (the border is becoming blue) and only after i click a second time on the exact same button it'll become green (the style that i'm giving it via setStyle).
However, the selected property becomes true on the first click and false on the second click, which means i click once on the button and it gets a blue border and selected = true, if i click on it a second time it becomes green and selected = false and if i click on it a third time it becomes normal again but selected will be true again.
I find it to be really strange that the first click on a button changes the "selected" variable correctly but not the style. Why is this happening and how can i avoid that i've to select the button first before i can click it?
You initialize
selected = false ;
and
setStyle(BASIC_STYLE);
But your event handler enforces the rule
selected == true -> setStyle(BASIC_STYLE);
selected == false -> setStyle(CLICKED_STYLE);
So your initial state is inconsistent with the state your handler enforces.
From the initial state, the first time you click, selected is set to true which causes setStyle(BASIC_STYLE) (which is the value it already has, so nothing changes). From then on, everything will switch as required.
You either need to change the initial state, or switch the logic of the setStyle(...) call in the handler.
public class ButtonEnterAction extends Button {
boolean selected = true;
public ButtonEnterAction(String connect) {
setText(connect);
action();
}
public ButtonEnterAction() {
action();
}
private void action() {
EventHandler<KeyEvent> enterEvent = (KeyEvent event) -> {
if (event.getCode() == KeyCode.ENTER) {
fire();
}
};
addEventFilter(KeyEvent.KEY_PRESSED, enterEvent);
// setOnMouseEntered(new EventHandler<MouseEvent>() {
// #Override
// public void handle(MouseEvent me) {
// SepiaTone st = new SepiaTone();
// setEffect(st);
// }
// });
// setOnMouseExited(new EventHandler<MouseEvent>() {
// #Override
// public void handle(MouseEvent me) {
// setEffect(null);
// }
// });
}
#Override
public void fire() {
super.fire(); //To change body of generated methods, choose Tools | Templates.
if (selected) {
SepiaTone st = new SepiaTone();
setEffect(st);
} else {
setEffect(null);
}
selected = !selected;
}
}
Create the Instant Class in ButtonEnterAction is like.
ButtonEnterAction bea = new ButtonEnterAction("TestButton");
bea.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("hello");
}
});
How can I trigger backspace key press event when button click.
private void doClick(char type)
{
jTextField1.dispatchEvent(new KeyEvent(jTextField1, KeyEvent.KEY_PRESSED, System.currentTimeMillis(),KeyEvent.SHIFT_DOWN_MASK, KeyEvent.VK_7, type));
jTextField1.dispatchEvent(new KeyEvent(jTextField1, KeyEvent.KEY_TYPED, System.currentTimeMillis(),KeyEvent.SHIFT_DOWN_MASK, KeyEvent.VK_UNDEFINED, type));
jTextField1.dispatchEvent(new KeyEvent(jTextField1, KeyEvent.KEY_RELEASED, System.currentTimeMillis(),KeyEvent.SHIFT_DOWN_MASK, KeyEvent.VK_7, type));
}
Im using this method to add one character when button click. Is there any mechanism to trigger backspace key press event like this.
Okay, before I answer the question, because I believe the approach is dirty, here are two, similar, concepts...
You could make use of the Action API, which would allow you to define self-contained units for work. These could be abstract to do the heavy lifting, in the particular case of inserting new values, but this demonstrates the use case of removing a character...
public class BackspaceAction extends AbstractAction {
private JTextField field;
public BackspaceAction(JTextField field) {
putValue(NAME, "Back-space");
this.field = field;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = field.getText();
if (!text.isEmpty()) {
int position = field.getCaretPosition();
if (position > 0) {
text = text.substring(0, position - 1) + text.substring(position);
field.setText(text);
field.setCaretPosition(Math.max(position - 1, 0));
}
}
}
}
Or through use the Document itself...
public class BackspaceAction extends AbstractAction {
private JTextField field;
public BackspaceAction(JTextField field) {
putValue(NAME, "Back-space");
this.field = field;
}
#Override
public void actionPerformed(ActionEvent e) {
Document doc = field.getDocument();
if (doc.getLength() > 0) {
int position = field.getCaretPosition();
if (position > 0) {
try {
doc.remove(position - 1, 1);
field.setCaretPosition(Math.max(position - 1, 0));
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}
}
}
Which would simply instantiated using something like...
JButton back = new JButton(new BackspaceAction(field));
If you're hell bent on trying to get into the nitty gritty low layers of the API, then something like....
char value = (char)8;
field.dispatchEvent(new KeyEvent(field, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE, value));
field.dispatchEvent(new KeyEvent(field, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, KeyEvent.VK_BACK_SPACE, value));
field.dispatchEvent(new KeyEvent(field, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, value));
might work. I say might, as this does work on Windows 7, but I make no guarantee if it will work on any other platforms or versions of Windows
Now, for me, I can look at the other two Actions and see what they are trying to do, I look at the key event approach and begin to scratch my head wondering why, but that's just me...
All Swing components have default Actions to perform this type of functionality. You may want to consider using the default "backspace Action" to do this.
If so then check out the ActionMapAction class is a simple wrapper class that will allow you to easily use the default Action for the component by creating the Action for you. For example the code would be:
JTextField textField = new JTextField();
Action backSpace = new ActionMapAction("Backspace", textField, "delete-previous");
backSpace.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_B);
JButton backSpaceButton = new JButton(backSpace);
You can use the Action with JButtons, JMenuItems. Make use of reusable code to leverage existing Actions of the Swing components.
I have a Navigator class and a custom DialogBox class which is descended from GridPane.
public DialogBox(final JDialog jdialog) {
Label lblKeyName = new Label("Enter New Key");
Label lblKeyType = new Label("Select Key Type");
TextField txtKeyName = new TextField();
ComboBox cboKeyType = new ComboBox();
txtKeyName.getText();
Button btnOk = new Button("OK");
Button btnCancel = new Button("Cancel");
btnOk.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
//TODO: Somehow return the values in the ComboBox and TextField
}
});
btnCancel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
jdialog.setVisible(false);
}
});
txtKeyName.prefWidth(300);
cboKeyType.prefWidth(300);
this.add(lblKeyName, 0, 0);
this.add(lblKeyType, 0, 1);
this.add(txtKeyName, 1, 0);
this.add(cboKeyType, 1, 1);
this.add(btnOk, 0, 2);
this.add(btnCancel, 1, 2);
}
This is the constructor for my DialogBox.
JFXPanel fxPanel = new JFXPanel();
testBox = new DialogBox(jdialog);
fxPanel.setScene(new Scene(testBox));
jdialog.add(fxPanel);
jdialog.setVisible(true);
How can I retrieve the values in the TextField and ComboBox? I can slightly recall a long ago class where the professor mentioned a technique involving the calling class (Navigator in this case) implementing an Interface and then passing itself to the DialogBox class to retrieve values. Unfortunately I have not found anything and cannot remember how it is done.
Assuming that the dialog is modal, basically, once btnOk or btnCancel button is pressed you need to change some kind of state flag which you can interrogate to determine how the dialog was closed...
// This will also handle the use case where the user presses the "x" button...
private boolean wasCancelled = true;
//...
public boolean wasCancelled() {
return wasCancelled;
}
In you action listeners, you need to set the state appropriately.
btnOk.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
wasCancelled = false;
jdialog.setVisible(false);
}
});
btnCancel.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
wasCancelled = true;
jdialog.setVisible(false);
}
});
Now, once the dialog returns, you need to check this flag...
jdialog.add(fxPanel);
jdialog.setVisible(true);
if (!jdialog.wasCancelled()) {
//...
}
You then need to supply "getter" methods to allow a caller to extract the values from the dialog...
public String getKey() {
return txtKeyName.getText();
}
public String getType() {
return cboKeyType.getSelectionModel().getValue();
}
This will mean you will need to create these two fields as instance variables
I have a menu with items that open internal frames, but every time I need to click twice in the frame. One time to give focus to the Int.frame and the second time to actually do something (give focus to a textfield).
So, here is my question: It's possible to automatic give focus to the Int.Frame?
Code of my main screen:
public final class principal extends javax.swing.JFrame {
viewCity city = new viewCity();
public principal() {
initComponents();
myListeners();
setLocationRelativeTo(null);
}
public void myListeners() {
menuCity.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
menuCityClicked(e);
}
});
}
public void central(JInternalFrame window1) {
int lDesk = panelPrincipal.getWidth();
int aDesk = panelPrincipal.getHeight();
int lIFrame = window1.getWidth();
int aIFrame = window1.getHeight();
window1.setLocation(lDesk / 2 - lIFrame / 2, aDesk / 2 - aIFrame / 2);
}
private void menuCityClicked(MouseEvent e) {
if (!city.isVisible()) {
panelPrincipal.add(city);
central(city);
city.requestFocus(); // Nothing
city.requestFocusInWindow(); // Nothing
city.setVisible(true);
city.requestFocus(); // Nothing
city.requestFocusInWindow(); // Nothing
}
}}
No matter what, the menu will always keep the focus. For example, click in your browser's menu, and you will keep the focus, by moving the cursor you will open other menus without need to click.
By putting the properties "selection model" to null works, but give me nullpointerexception.
Ok, the problem is with the jMenu, but with jMenuItem Works fine, so... I'm using