So, I'm trying to delete the highlighted row in TableView in my program.
I've looked at loads of tutorials online, but really can't get my head around this.
I have followed the example from CodeMakery, which is in Eclipse, but I'm unable to get it to work on IntelliJ (because of some apparent JDK problems?)
This is the code from CodeMakery:
private void handleDeletePerson() {
int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
personTable.getItems().remove(selectedIndex);
} else {
// Nothing selected.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No Person Selected");
alert.setContentText("Please select a person in the table.");
alert.showAndWait();
}
}
Could you please help me understand how to make selected row get deleted?
just add at the beginning of this method personTable.setEditable(true). Should work now.
Related
so I am using JavFX to create a form that stores all the answers in a csv file. I need to create a dropdown menu that allows the users to select an option, which is then recorded in the csv file. I have tried a lot of different options, however I think comboBox is the best option.
I have no problem creating the ComboBox, I only run into problems when it comes to the method to get the value of the box.
Can someone help me find a solution, or suggest what another JavaFX menu I can use?
This is the code I have right now:
public VBox setFamiliar(){
Button button = new Button();
button.setOnAction(e -> toString());
familiarComboBox = new ComboBox<>();
familiarVBox = new VBox();
familiarComboBox.getItems().addAll("Irmão", "Irmã", "Avó", "Avô", "Tio", "Tia", "Pai", "Mãe");
familiarVBox.getChildren().add(familiarComboBox);
familiarVBox.getChildren().add(button);
return familiarVBox;
}
Here I set the ComboBox, this part doesnt seem to have a problem because it appears and I can select an item. I created a separate void toString() method that sets the value of a variable to the current selected item
public void toString(ActionEvent e){
familiar = familiarComboBox.getSelectionModel().getSelectedItem().toString();
}
The problem is then in the get method to get the value that was selected.
public String getIrmao(){
if(familiar.equals("Irmão")){
return "2";
}
return "0";
I also tried to do familiarComboBox.getSelectionModel().getSelectedItem().equals(), and other variations of this combination.
If I understand your requirement -- that when a user makes a choice from the "Familiar" combo box, a value should be written immediately to a CSV file -- you don't need the getIrmao() method. You simply write the value out in the action which you are calling toString(...) (not a good choice of names), but which we will rename to handleFamiliarChange(...).
Now the method becomes
public void handleFamiliarChange(ActionEvent e){
final String familiar =
familiarComboBox.getSelectionModel().getSelectedItem().toString();
FileUtils.writeToCsvFile(familiar.equals("Irmão") ? 2 : 0);
}
where FileUtils.writeToCsvFile(...) is a method that does the file writing. Note that FileUtils is a class you have created to separate out file handling concerns -- your JavaFX view class should only concern itself with views.
http://code.makery.ch/blog/javafx-dialogs-official/ shows how to get the stage of a JavaFX-8 dialog:
// Get the Stage.
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
Alas, this does not work for me: the dialog pane (although displayed) gives null on .getScene().
Is there any other easy way to get the stage or at least the scene of an open dialog window?
The background of the question is that, under certain circumstances, need to display an Alert to the user while keeping the underlying dialog window open. Currently, that does not work due to an invalid combination of Modality values, but that's a different topic.
Hard to say for sure if you post no context code but I think the problem is the timing. You need to get the stage before you showAndWait (or at least before the dialog is closed). Try this:
public static boolean showConfirmationDialog(String contentText, String headerText) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, contentText, ButtonType.YES, ButtonType.NO);
alert.setTitle("Test");
alert.setHeaderText(headerText);
Window alertWindow = alert.getDialogPane().getScene().getWindow();
System.out.println("alertWindow.getOpacity(): " + alertWindow.getOpacity());
Optional<ButtonType> result = alert.showAndWait();
//This would cause a NullPointerException at this point:
//alertWindow = alert.getDialogPane().getScene().getWindow();
//System.out.println("alertWindow.getOpacity(): " + alertWindow.getOpacity());
return (result.get() == ButtonType.YES);
}
I'm trying to implement the following thing: when a specific button is clicked, a new dialog appears where the user has to enter some information and to check/uncheck some checkboxes. Then the user can either click "OK" or "Cancel".
If he clicks "OK" the information he entered is checked for correctness. If something is not correct the dialog should appear again with a warning message and the user should correct/re-enter the information. I would like the information the user entered to be stored. So, if the information is not correct, the dialog should not "reset" to the initial state but keep the information the user entered.
If the user clicks "Cancel" some standard values are used further.
I almost got a solution, but it is not working properly. When using my solution: when I enter a wrong information and click "OK" a warning appears and the information is stored and I can edit it. But if I enter wrong information again and click "OK" again, then the wrong information is accepted. Please see my code below.
QDialog dialog(this);
QFormLayout form(&dialog);
form.addRow((new QLabel("Please enter the three questions for the P835 test. \n"
"Questions one and two will be permuted, \n "
"question three will not. Below each question enter \n"
"the rating scale starting with the best rating and \n"
"separate the ratings with a comma.")));
QList<QLineEdit *> fields;
QLineEdit *lineEdit_Q1 = new QLineEdit(&dialog);
lineEdit_Q1->setText("Bitte bewerten Sie die Signalqualität!");
QString label_Q1 = QString("First question:");
form.addRow(label_Q1, lineEdit_Q1);
fields << lineEdit_Q1;
QLineEdit *lineEdit_Q1_answer = new QLineEdit(&dialog);
lineEdit_Q1_answer->setText("nicht verzerrt, leicht verzerrt, etwas verzerrt, ziemlich verzerrt, sehr verzerrt");
QString label_Q1_answer = QString("Rating first question:");
form.addRow(label_Q1_answer, lineEdit_Q1_answer);
fields << lineEdit_Q1_answer;
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
form.addRow(&buttonBox);
QObject::connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
QObject::connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
bool click = true;
int code = dialog.exec();
bool passed = true;
while (click == true){
passed = true;
if (code == QDialog::Accepted) {
// check if empty questions were entered
if (lineEdit_Q1->text() == "" || lineEdit_Q2->text() == "" || lineEdit_Q3->text() == "") {
QMessageBox msgBox;
msgBox.setText("An error occured while entering questions for the P835 test");
msgBox.setInformativeText("You can not enter empty questions! Please try again or click cancel to use the standard questions!");
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
passed = false;
dialog.close();
dialog.exec();
break;
}
if (lineEdit_Q1_answer->text().split(",").size() != 5 || lineEdit_Q2_answer->text().split(",").size() != 5 || lineEdit_Q3_answer->text().split(",").size() != 5) {
QMessageBox msgBox;
msgBox.setText("An error occured while entering question ratings for the P835 test");
msgBox.setInformativeText("You have to enter exactly 5 ratings for each question! Please try again or click cancel to use the standard ratings!");
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
passed = false;
dialog.close();
dialog.exec();
break;
}
if (oneFileCheckBox->isChecked() && multipleFilesCheckBox->isChecked()) {
QMessageBox msgBox;
msgBox.setText("An error occured while setting up the P835 test...");
msgBox.setInformativeText("You cannot check both boxes! Please select only one option for the files!");
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
passed = false;
dialog.close();
dialog.exec();
break;
}
if (oneFileCheckBox->isChecked() == false && multipleFilesCheckBox->isChecked() == false) {
QMessageBox msgBox;
msgBox.setText("An error occured while setting up the P835 test...");
msgBox.setInformativeText("You have to select one file option!");
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
passed = false;
dialog.close();
dialog.exec();
break;
}
if (passed == true) {
this->configMgr->setQuestions(lineEdit_Q1->text(), lineEdit_Q2->text(), lineEdit_Q3->text());
this->configMgr->setAnswers(lineEdit_Q1_answer->text(), lineEdit_Q2_answer->text(), lineEdit_Q3_answer->text());
if(oneFileCheckBox->isChecked() == true) {
this->configMgr->fileOption = 0;
}
if(multipleFilesCheckBox->isChecked() == true) {
this->configMgr->fileOption = 1;
}
QMessageBox msgBox;
msgBox.setText("Success!");
msgBox.setInformativeText("The questions and the question ratings have been set successfully!");
msgBox.setIcon(QMessageBox::Information);
msgBox.exec();
dialog.close();
click = false;
}
if (code == QDialog::Rejected) {
this->configMgr->setQuestions(Q1_std, Q2_std, Q3_std);
this->configMgr->setAnswers(Q1_std_answer, Q2_std_answer, Q3_std_answer);
QMessageBox msgBox;
msgBox.setText("Setting standard values...");
msgBox.setInformativeText("Standard questions and ratings will be set. Click on the P835 button again to set questions and ratings manually!");
msgBox.setIcon(QMessageBox::Information);
msgBox.exec();
dialog.close();
click = false;
}
}
if (code == QDialog::Rejected) {
this->configMgr->setQuestions(Q1_std, Q2_std, Q3_std);
this->configMgr->setAnswers(Q1_std_answer, Q2_std_answer, Q3_std_answer);
QMessageBox msgBox;
msgBox.setText("Setting standard values...");
msgBox.setInformativeText("Standard questions and ratings will be set. Click on the P835 button again to set questions and ratings manually!");
msgBox.setIcon(QMessageBox::Information);
msgBox.exec();
dialog.close();
click = false;
}
}
In this example code I only put one text box where the user has to enter some information. I have six text boxes and two checkboxes.
I hope you can help me! Thank you!
You should use validation with QDialog::done(int r) or a QWizard. Qt makes this task relatively easy if you take the time to study the examples and documentation on it, but it does take time to learn it the first time.
Validation with QDialog::done(int r)
http://www.qtcentre.org/threads/8048-Validate-Data-in-QDialog
void DataSourceDlg::done(int r)
{
if(QDialog::Accepted == r) // ok was pressed
{
if(nodeLineEdit->text().size() > 3) // validate the data somehow
{
QDialog::done(r);
return;
}
else
{
statusBar->setText("Invalid data in text edit...try again...");
return;
}
}
else // cancel, close or exc was pressed
{
QDialog::done(r);
return;
}
}
Note that by subclassing QDialog and managing the done method you can prevent the dialog from closing and display a message.
QWizard and QWizardPage
http://doc.qt.io/qt-5/qwizard.html#details
Using a QWizard is a little more work, but it is built around validation and ensuring the correct information is in the right boxes.
Basically you subclass QWizard and QWizard page, and then you implement validatePage() and some others methods and you follow the examples and it works flawlessly. This used to be included in Qt Solutions and it was opened up a few years ago.
http://doc.qt.io/qt-5/qtwidgets-dialogs-classwizard-example.html
http://doc.qt.io/qt-5/qtwidgets-dialogs-licensewizard-example.html
companyLabel = new QLabel(tr("&Company name:"));
companyLineEdit = new QLineEdit;
companyLabel->setBuddy(companyLineEdit);
emailLabel = new QLabel(tr("&Email address:"));
emailLineEdit = new QLineEdit;
emailLineEdit->setValidator(new QRegExpValidator(QRegExp(".*#.*"), this));
emailLabel->setBuddy(emailLineEdit);
postalLabel = new QLabel(tr("&Postal address:"));
postalLineEdit = new QLineEdit;
postalLabel->setBuddy(postalLineEdit);
registerField("details.company*", companyLineEdit);
registerField("details.email*", emailLineEdit);
registerField("details.postal*", postalLineEdit);
* makes a field mandatory. QRegExpValidator makes sure the email address has an # sign in the middle.
QValidator with QLineEdit
http://doc.qt.io/qt-5/qvalidator.html#details
http://doc.qt.io/qt-5/qtwidgets-widgets-lineedits-example.html
validatorLineEdit->setValidator(new QIntValidator(
validatorLineEdit));
validatorLineEdit->setValidator(new QDoubleValidator(-999.0,
999.0, 2, validatorLineEdit));
QLineEdit::setInputMask(QString)
http://doc.qt.io/qt-5/qlineedit.html#inputMask-prop
inputMaskLineEdit->setInputMask("");
inputMaskLineEdit->setInputMask("+99 99 99 99 99;_");
inputMaskLineEdit->setInputMask("0000-00-00");
inputMaskLineEdit->setText("00000000");
inputMaskLineEdit->setCursorPosition(0);
inputMaskLineEdit->setInputMask(">AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#");
Regular Expressions
RegEx is awesome. Learning it is extremely useful (IMHO). I really like the tools and cheatsheets provided by gskinner. http://regexr.com/
http://doc.qt.io/qt-5/qregexpvalidator.html#details
// regexp: optional '-' followed by between 1 and 3 digits
QRegExp rx("-?\\d{1,3}");
QValidator *validator = new QRegExpValidator(rx, this);
QLineEdit *edit = new QLineEdit(this);
edit->setValidator(validator);
Hope that helps.
I need to finish edit QTableWidget when some event happend.
MyWindow::onSomeEvent
{
// Finish ui->table editing
//...
}
How can I do this?
The event is a spinbox editing. When it happend rows count becomes equled its value.
I tried to send enter key press event. But when editing item in the last row and new rows count is less then current it does not work.
QKeyEvent *ev = new QKeyEvent(QEvent::KeyRelease,
Qt::Key_Return,
Qt::NoModifier);
QApplication::sendEvent(ui->table, ev);
ui->table->setRowCount(value);
QApplication::sendEvent(ui->table, ev);
Try this:
MyWindow::onSomeEvent()
{
QKeyEvent *ev = new QKeyEvent(QEvent::KeyRelease,Qt::Key_Return,Qt::NoModifier);
QApplication::sendEvent(ui->tableWidget,ev);
}
You just emulate Enter pressing when something happens.
I am trying to switch to a New window which gets displayed when I click on the Debt Pricing Template. But I am unable to do that as a result of which I am not able to proceed with further scripting... The problem is I am not able to know what should I pass in the switchTo.window() because Pricing Approval Gateway window displays and following is the HTML for the new window:
<*h1 class="pageType noSecondHeader">Pricing Approval Gateway<*/h1>
Following is the code:
LoginPage2.driver.findElement(By.linkText("TEST ORG")).click();
System.out.println("3.Select Dept pricing template button from the organization detail page.");
if(LoginPage2.driver.findElement(By.name("debt_pricing_template")).isDisplayed())
System.out.println("User should able to navigate to Dept pricing template and template display few question, user have answer these question for further navigation.");
LoginPage2.driver.findElement(By.name("debt_pricing_template")).click();
LoginPage2.driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
LoginPage2.driver.switchTo().window("bPageTitle");
Please advise what needs to be added?
I never used it because in my tests I am not using any new windows, but this should help:
Set<string> handlers = driver.getWindowHandles();
if (driver.getWindowHandles().size()>= 1){
for(String handler : handlers){
driver.switchTo().window(handler);
if (driver.getElement(By.tagName("h1")).contains("Pricing")){
System.out.println("Get focus on Popup window");
break;
}
}
}
else System.out.println("No windows founded!");
I am not quite sure with the h1 approach. So if it does not help, try before opening new window storing current window to String:
String mainWindow = driver.getWindowHandle();
Then click the link (or do something else as you are doing now) to open new window. Then to switch to the new window:
Set<string> handlers = driver.getWindowHandles();
for (String handler : handlers){
if (!handler.equals(mainWindow)){
driver.switchTo(handler);
break;
}
}
And then to switch back to original window just do:
driver.switchTo(mainWindow);
Ofcourse the driver variable is expected live instance of
WebDriver
driver.findElement(By.linkText("Go to Billing Summary")).click();
driver.findElement(By.linkText("01 Mar 2016")).click();
Thread.sleep(5000);
driver.findElement(By.linkText("AMS TAX")).click();
driver.findElement(By.linkText("00842")).click();
Set<String> instancewindow= driver.getWindowHandles();
Iterator<String> it = instancewindow.iterator();
String parent =it.next();
String child = it.next();
driver.switchTo().window(child);
driver.switchTo().frame("modalSubWindow");
driver.findElement(By.linkText("View More Vehicle Details>>")).click();
driver.switchTo().window(parent);