Use QMessageBox to choose from a list of options - java

I'm newly moving from Java to Qt, and I have a question. In JOptionPane you can pass an array of choices and JOptionPane will automatically make a combo box for the user to select a choice from. Is something analogous to this possible in Qt with QMessageBox or another native Qt element?

You should use QInputDialog::getItem(). For example:
QStringList fruits;
fruits << "Apple" << "Banana" ... ;
QString fruit = QInputDialog::getItem(this, "Select fruit", "Fruit:", fruits);

You could just read QMessageBox reference.
I am copy-pasting code sample from it:
QMessageBox msgBox;
msgBox.setText("The document has been modified.");
msgBox.setInformativeText("Do you want to save your changes?");
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Save);
int ret = msgBox.exec();
switch (ret) {
case QMessageBox::Save:
// Save was clicked
break;
case QMessageBox::Discard:
// Don't Save was clicked
break;
case QMessageBox::Cancel:
// Cancel was clicked
break;
default:
// should never be reached
break;
}
This code creates a message box with three buttons (Save, Discard, Cancel). Save button is focused.
You can combine values from Standard buttons using bitwise OR operator in setStandardButtons function.
If you need some options known only at runtime I can propose this possible solution.
QMessageBox msgBox;
//set common message box parameters. (informative text, etc)
//iterate through possible options. For each possible option:
{
QPushButton *button = msgBox.addButton(myQStringOption, QMessageBox::AcceptRole);
connect(button, SIGNAL(clicked()), /* response object */, SLOT(/*response slot*/));
}
msgBox.exec();
I am not sure this is the most elegant solution but it should works.
If you don't want to use signals and slots you could use clickedButton() method to determine which button was pressed.
msgBox.exec();
if ((msgBox.clickedButton())->text() == myQStringOption){
//doStuff
}

Related

Multiple classes with Mouse.next()

As the title already shows I have an issue with the function "Mouse.next()".
I'm programming my own buttons at the moment and for that I have to check, if the left mouse-button was pressed. I thought, that I can do it so:
while(Mouse.next()) {
if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0) {
// some code..
}
}
This also works, if I only have one instance of my button. But if I add another instance the while loop never gets called for the second (last created) button...
Does somebody have any idea, why this could happen?...
And also what do these functions (found them on the internet) Mouse.getEventButtonState(), Mouse.getEventButton() == 0 and Mouse.isButtonDown(0)
Mouse is from org.lwjgl.input.Mouse
With another instance I mean something like: MyButton button = new MyButton();
EDIT:
My Question is: How can I get Mouse.next() to work with multiple instances of the surrounding class...
Because Mouse is a Singleton . As long as it is Singleton calling next will consume the Event. You can not consume the same event two times! When first object calls next() it consumes it and when the second calls next() the is no second click to consume.
The issue is that getEventButton() returns a different number depending on which button was pressed. What you should do instead is something like:
while (Mouse.next()) {
if (Mouse.getEventButtonState()) {
int buttonId = Mouse.getEventButton();
switch (buttonId) {
case -1: break; // no button was clicked
case 0:
// code for first button
break;
case 1:
// code for second button
break;
}
}
}

Displaying "Correct" and "Wrong" in JAVA

I'm making a simple quiz program. I need to display my Correct and Wrong it depends on the answer of the user. I think it is in the IF else. That's why I can't get it through. When I run it. I choose the correct answer. It is still displaying "Wrong!" and it counts it as correct. and Then change to different number. It is still displaying "Wrong!". I'm using checkbox as the multiple choice of the quiz.
Here's my code:
if(C1.getState()) // if the user chooses the checkbox c1
{
outputlabel.setText("Correct\n");
CorrectAnswer++; // it will count one point per correct answer.
}else
outputlabel.setText("Wrong!\n");
if(C13.getState()) // if the user chooses the checkbox C13
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C19.getState()) // if the user chooses the checkbox C19
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C21.getState()) // if the user chooses the checkbox C21
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C27.getState()) // if the user chooses the checkbox C27
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
CorrectLabel.setText("Correct Answers: "+CorrectAnswer);
score =(CorrectAnswer*100)/5; // average of the quiz
if (score>=75)
{
scorelabel.setText("Grade: "+score+ "% ");
}else{
scorelabel.setText("Grade: "+score+"%.");
repaint();}
}
}
I'm not entirely sure what you're trying to do in the code. For each you're checking if it is set, and then you're setting the outputlabel value. So if the first checkbox is checked it will set the outputlabel text to "Correct". And if any of the other checkboxes are not checked it will then simply override what you did before and set the label to "Wrong".
Maybe you want separate outputlabels for each of the checkboxes?
You should have one final output label, after you check the state of all the correct answers. And based on the correct answers count, you can set the final output label.

Using Boolean True/False with JOptionPane.YES_NO_OPTION

I have a series of four yes/no choices in four separate dialog boxes, the cumulative results of which will lead to one of twelve separate links (e.g., Yes/Yes/Yes/No -> link A, Yes/No/No/Yes -> link B, etc). The branching logic uses boolean values.
Here's what I have so far...just the first dialog box and printing the results for validation.
public class OutageGuideSelector{
public static void main(String[] args){
boolean contactServerUp;
boolean vistaUp;
boolean stormOutage;
boolean vistaCSUp;
//
int contactServerEntry = JOptionPane.showConfirmDialog(null,
"Is the contact server up", "Please select",
JOptionPane.YES_NO_OPTION);
System.out.println("result from entry " + contactServerEntry);
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
/* System.out.println(contactServerUp); */
}}
Right now, the results of clicking YES reults in a 0 being returned, NO results in a 1. Is this normal, seems counterintuitive, and there's nothing at docs.oracle.java that shows a clear example of the output values except this which seems to suggest that the public static final int YES_NO_OPTION default in 0.
Additionally, the line System.out.println(contactServerUp); comes back with an error that the field contactServerUp might not have been initialized when I un-comment it, so I can't see if my convert-int-to-boolean is working.
First: It appears that JOptionPane method does not include any boolean returns...except getWantsInput() which returns the value of the wantsInput property...so I assume I'm already being the most efficient I can with this. I'd like to know if there's an easier way.
Second, what am I missing that prevents my console output statement from recognizing the contactServerUp? Where's my misplaced semicolon?
According to the javadoc, when one of the showXxxDialog methods returns an integer, the possible values are:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
You should test against those constants:
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
The value returned by the the JOptionPane dialogs are values defined as constant fields in the class.
Although, indeed, one could assume that 0 means false and 1 means true, the values are more ids for the different buttons a dialog can have.
To know if the user pressed yes or no, you can compare the return value to the constant fields described here. For example, in your case :
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
Since a dialog a JOptionPane can have more than two possible 'answers' a boolean would be a poor representation. You are forgetting about the YES, NO and CANCEL option, or what about just a OK answer.
If it would have been written today, I suspect a Enum would have been used instead of an int.
As for the second question, the compiler does not allow access to uninitialized variables.
When you do the following, there is a chance that the variable might not be initialized:
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
What if, for example, contactServerEntry == JOptionPane.CLOSED_OPTION? In that case, your boolean value is never initialized.
You need to add an else clause at the end of your if-else chain, or initialize contactServerUp value to a default value in the beginning.

How to submit multiple vales from form control to the database

I have 8 MC questions in a panel. When submitted, I want all the selected answer to be recorded in the database. However, my code is only recording 1 question. Here is the code. (Note: All the jRadioButton names are not same since they are in one panel together.)
Here is the code :
public void submitButtonClicked(){
for(int i=1;i<9;i++){
username = "Smith";
questionID = i;
if(jRadioButton1.isSelected()){answer = jRadioButton1.getText();}
else if(jRadioButton2.isSelected()){answer = jRadioButton2.getText();}
if(jRadioButton3.isSelected()){answer = jRadioButton3.getText();}
else if(jRadioButton4.isSelected()){answer = jRadioButton4.getText();}
// and So on until the question 8.
}
Consider creating an array or ArrayList of the ButtonGroups for each JRadioButton cluster. You can then use a for loop to get the selection from each ButtonGroup which is the model of the JRadioButton selected, and if not null, get its actionCommand String.
For example, please look at my code here.
In your solution only one value is recorded because if one if statement is executed then it will bypass all other else if statements.
You could create a array of jradiobuttons and then use them in for loop,traversing each button one by one and then recording its answer.

GWT telephone number masking

Does anyone know how to go about creating field that would perform telephone number format masking, like here (___) ___-____:
http://www.smartclient.com/smartgwt/showcase/#form_masking
A better approach would be to let the user type whatever they want: "789-555-1234" or "(789) 555-1234" or "7895551234" and then when the field loses focus decide if what they typed can be a phone number. If so you can reformat it as "(789) 555-1234". There are several related questions about how to do that sort of thing with regular expressions; just be sure your regex accepts the format you're changing the user's input to, otherwise it will be really annoying to edit.
As an example, look what happens when you type ".5" into the left margin field in Microsoft's standard page setup dialog: when you tab out it changes it to "0.5".
UPDATE: Here's sample code in GWT to illustrate. For the sake of this example, assume there's an element called "phoneContainer" to put the text box in. GWT doesn't give you the full java.util.regex package, but it gives enough to do this:
private void reformatPhone(TextBox phoneField) {
String text = phoneField.getText();
text = text.replaceAll("\\D+", "");
if (text.length() == 10) {
phoneField.setText("(" + text.substring(0, 3) + ") " + text.substring(3, 6) + "-" + text.substring(6, 10));
}
}
public void onModuleLoad() {
final TextBox phoneField = new TextBox();
RootPanel.get("phoneContainer").add(phoneField);
phoneField.addBlurHandler(new BlurHandler(){
public void onBlur(BlurEvent event) {
reformatPhone(phoneField);
}
});
}
It looks like you'd want to create your own widget that extends the GWT input box and has a default value set to the mask you want. Then you handle the onKeypress event and update the field as needed (making sure to set the cursor position to the correct location).

Categories