What I am trying to achieve is that I want my if statement to check if my method verifyAnswer returns true, and if it does I want it to cancel my timer. So I searched up how to do the following but the answer I found all said similar things, however I think that since my argument in the method depends on a user answer it isn't working. This seems simple but I am new to Java and can't seem to make it work. Thank you all for the help!
public boolean verifyAnswer(String userAnswer) {
String correctAnswer = this.questions.get(currentQuestionIndex).correctAnswerText;
if(userAnswer.equals(correctAnswer)) {
timer.pauseTimer();
JOptionPane.showMessageDialog(null, "Correct Answer");
return true;
}
else {
timer.pauseTimer();
JOptionPane.showMessageDialog(null, "Wrong Answer");
return false;
}
}
Timer t = new Timer();
int[] score = {0};
TimerTask tt = new TimerTask() {
#Override
public void run() {
System.out.println(++score[0]);
if (score[0] == 30) {
t.cancel();
}
else if(verifyAnswer()) { //Why doesn't this line work?
t.cancel();
}
};
};
t.scheduleAtFixedRate(tt, 0, 1000);
Below is a label with an action listener, so when the user clicks on it, it checks the text that is in the label with the verifyAnswer method to see if the user chose correctly.
label_option_a = new JLabel("<html>Option A</html>");
label_option_a.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
verifyAnswer(label_option_a.getText());
}
});
Because you are not passing an argument in verifyAnswer method. verifyAnswer expect string parameter.
public boolean verifyAnswer(String userAnswer) { .. }
You should call like this
else if(verifyAnswer("pass_what_argument_you_want_to_pass_for_user_answer")) {
t.cancel();
}
You should change true and false returns in your method. Like that
public boolean verifyAnswer(String userAnswer) {
String correctAnswer = this.questions.get(currentQuestionIndex).correctAnswerText;
if(userAnswer.equals(correctAnswer)) {
timer.pauseTimer();
JOptionPane.showMessageDialog(null, "Correct Answer");
return false;
}
else {
timer.pauseTimer();
JOptionPane.showMessageDialog(null, "Wrong Answer");
return true;
}
}
i am helping my friend on a project
i have tried to add aditional events between the if statements but when i add them it seems top wrok properly is there any way to check is the radio button is selected as .isChecked doesn 't work for some weird reason
private void btnPreveriMouseClicked(java.awt.event.MouseEvent evt) {
String compare = lblVprasanje.getText();
if (compare.equals("question")) {
if (rbtOdgovor3.isSelected()) {
new Correct().setVisible(true);
this.dispose();
} else {
new Wrong().setVisible(true);
this.dispose();
}
}
if (compare.equals("hello")) {
if (rbtOdgovor2.isSelected()) {
new Correct().setVisible(true);
this.dispose();
} else {
new Wrong().setVisible(true);
this.dispose();
}
}
if (compare.equals("question")) {
new DrugaStopnja().setVisible(true);
if (rbtOdgovor3.isSelected()) {
new Correct().setVisible(true);
this.dispose();
} else {
new Wrong().setVisible(true);
this.dispose();
}
}
if (compare.equals("question")) {
if (rbtOdgovor1.isSelected()) {
new Correct().setVisible(true);
this.dispose();
} else {
new Wrong().setVisible(true);
this.dispose();
}
}
well if the correct radio button is selected the "correct" window should open but if the wrong one is the "wrong " window should. I dont understand why the .isSelected() is not working
I've created a class to display a modeless dialog box. I want to warn the user of something but I can not prevent them from accessing the application.
In the Test program below, the Dialog will only be created 3 times(same issue i see in my app), then it stops. Have no idea why. if i remove the line dialog.setModalityType(Dialog.ModalityType.MODELESS); ,everything works fine. Another thing is that if I set a breakpoint in the show() method it will hit the breakpoint, if I continue it will show the box 3 more times and stop. Is there something wrong with this code? Don't have much experience with this stuff, but i'm thinking that the while() loop is causing an issue, but I can figure why?
public class JavaApplication6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
while (true) {
showAlertBox();
}
}
public static void showAlertBox() {
AlertBox box = new AlertBox("Test" , "HI THERE");
int result = box.show();
if (result == JOptionPane.YES_OPTION) {
System.out.println("YES SELECTED");
}
}
}
public class AlertBox {
JOptionPane pane;
JDialog dialog;
Object selectedValue;
String mTitle;
public AlertBox(String title, String alertText) {
pane = new JOptionPane(alertText, JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION, null, null, null);
mTitle=title;
}
public int show() {
dialog = pane.createDialog(null, mTitle );
dialog.setModalityType(Dialog.ModalityType.MODELESS);
dialog.setVisible(true);
selectedValue = pane.getValue();
while (selectedValue == JOptionPane.UNINITIALIZED_VALUE) {
//wait
selectedValue = pane.getValue();
}
if(selectedValue instanceof Integer) {
return ((Integer)selectedValue).intValue();
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
I have a table that has a JDialog for add new record, When i click to add Button and want to add a new record and JDialog opened, I close JDialog window and it returns null for my all columns of my table rows.
This is my JDialog constructor:
public class AddBookDialog extends JDialog implements ActionListener {
public AddBookDialog(JFrame owner) {
super(owner, "Add New Book", true);
initComponents();
saveBtn.addActionListener(this);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cancelBtn) dispose();
else if (e.getSource() == saveBtn) saveAction();
}
}
public void saveAction() {
if (nameTf.getText().trim().length() != 0) {
if (!haveDigit(nameTf.getText().trim())) setBookName(nameTf.getText().trim());
else {
JOptionPane.showMessageDialog(null, "Book Name have digit");
return;
}
} else {
JOptionPane.showMessageDialog(null, "Enter Book Name");
return;
}
if (isbnTf.getText().trim().length() != 0) {
if (haveSpace(isbnTf.getText().trim()) || haveLetter(isbnTf.getText().trim())) {
JOptionPane.showMessageDialog(null, "Enter Correct ISBN");
return;
}
setIsbn(isbnTf.getText().trim());
} else {
JOptionPane.showMessageDialog(null, "Enter Book ISBN");
return;
}
setBorrowStatus("No");
setDate(dateGenerate());
dispose();
}
I try to control this problem in my table GUI class:
public class BookPage_Admin extends JFrame implements ActionListener {
...
public void addAction() {
AddBookDialog dialog = new AddBookDialog(this);
if (dialog.getBookName() != null && dialog.getIsbn() != null && dialog.getBorrowStatus() != null &&
dialog.getDate() != null) {
Object[] added = new Object[]{dialog.getBookID(), dialog.getBookName(), dialog.getIsbn(), dialog.getBorrowStatus(), dialog.getDate()};
model.addRow(added);
}
}
}
But still when i close it, it returns null for my row.
How to prevent returning null when close it?
Just in case if no one will answer you:
When you initiate Dialog, aka AddBookDialog dialog = new AddBookDialog(this); you can override ActionListener on the Frame side like:
AddBookDialog dialog = new AddBookDialog(this);
dialog.setModal(true);
dialog.getSaveBtn().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] added = new Object[]{dialog.getBookID(), dialog.getBookName(), dialog.getIsbn(), dialog.getBorrowStatus(), dialog.getDate()};
model.addRow(added);
}
});
// importent set visible after ActionListener!!
dialog.setVisible(true);
Hope it will help,
In order to have custom button captions in an input dialog, I created the following code:
String key = null;
JTextField txtKey = new JTextField();
int answerKey = JOptionPane.showOptionDialog(this, new Object[] {pleaseEnterTheKey, txtKey}, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, okCaption);
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
How can I move the focus (cursor) to the text field as the dialog is displayed?
UPDATE
This does not work for me, I mean the textfield has no focus:
OS: Fedora - Gnome
public class Test {
public static void main(String[] args) {
String key = null;
JTextField txtKey = new JTextField();
txtKey.addAncestorListener(new RequestFocusListener());
int answerKey = JOptionPane.showOptionDialog(null, new Object[]{"Please enter the key:", txtKey}, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"OKKK", "CANCELLLL"}, "OKKK");
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
}
}
Dialog Focus shows how you can easily set the focus on any component in a modal dialog.
public static String getPassword(String title) {
JPanel panel = new JPanel();
final JPasswordField passwordField = new JPasswordField(10);
panel.add(new JLabel("Password"));
panel.add(passwordField);
JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
#Override
public void selectInitialValue() {
passwordField.requestFocusInWindow();
}
};
pane.createDialog(null, title).setVisible(true);
return passwordField.getPassword().length == 0 ? null : new String(passwordField.getPassword());
}
passing null as the last argument is the solution. At least it worked for me.
String key = null;
JTextField txtKey = new JTextField();
int answerKey = JOptionPane.showOptionDialog(this, new Object[] {pleaseEnterTheKey, txtKey}, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, null);
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
But even this solution bring another problem:
Focused component and Default component are different. Default component or default button is the button which its onclick fires if you press ENTER KEY.The last argument define the default component which gets the focus too and passing null brings the problem of having no default component!
I solved it for my code this way but I guess it is not a best practice:
String key = null;
final JTextField txtKey = new JTextField();
txtKey.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == 10) { //enter key
Container parent = txtKey.getParent();
while (!(parent instanceof JOptionPane)) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
final JPanel pnlBottom = (JPanel) pane.getComponent(pane.getComponentCount() - 1);
for (int i = 0; i < pnlBottom.getComponents().length; i++) {
Component component = pnlBottom.getComponents()[i];
if (component instanceof JButton) {
final JButton okButton = ((JButton)component);
if (okButton.getText().equalsIgnoreCase(okCaption)) {
ActionListener[] actionListeners = okButton.getActionListeners();
if (actionListeners.length > 0) {
actionListeners[0].actionPerformed(null);
}
}
}
}
}
}
});
I had the same problem with the RequestFocusListener() not working on Linux, after following the discussion on http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5018574 I found that adding an invokeLater fixed it for now...
public class RequestFocusListener implements AncestorListener
{
public void ancestorAdded(final AncestorEvent e)
{
final AncestorListener al= this;
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
JComponent component = (JComponent)e.getComponent();
component.requestFocusInWindow();
component.removeAncestorListener( al );
}
});
}
public void ancestorMoved(AncestorEvent e) {}
public void ancestorRemoved(AncestorEvent e) {}
}
The trick is to (a) use an AncestorListener on the text component to request focus, and when the focus is lost again (given to the default button), ask for focus a second time using a FocusListener on the text component (but don't keep asking for focus after that):
final JPasswordField accessPassword = new JPasswordField();
accessPassword.addAncestorListener( new AncestorListener()
{
#Override
public void ancestorRemoved( final AncestorEvent event )
{
}
#Override
public void ancestorMoved( final AncestorEvent event )
{
}
#Override
public void ancestorAdded( final AncestorEvent event )
{
// Ask for focus (we'll lose it again)
accessPassword.requestFocusInWindow();
}
} );
accessPassword.addFocusListener( new FocusListener()
{
#Override
public void focusGained( final FocusEvent e )
{
}
#Override
public void focusLost( final FocusEvent e )
{
if( isFirstTime )
{
// When we lose focus, ask for it back but only once
accessPassword.requestFocusInWindow();
isFirstTime = false;
}
}
private boolean isFirstTime = true;
} );
Better way to do it: create the JOptionPane using the constructor, override selectInitialValue to set the focus, and then build the dialog using createDialog.
// Replace by the constructor you want
JOptionPane pane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
#Override
public void selectInitialValue() {
textArea.requestFocusInWindow();
}
};
JDialog dialog = pane.createDialog(owner, title);
dialog.setVisible(true);
Try this
String key = null;
JTextField txtKey = new JTextField();
Object[] foo = {pleaseEnterTheKey, txtKey};
int answerKey = JOptionPane.showOptionDialog(this, foo, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] {okCaption, cancelCaption}, foo[1]);
if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
key = txtKey.getText();
}
I found a solution !
Very primitive, but works.
Just jump to the field by java.awt.Robot using key "Tab".
I've created utils method calls "pressTab(..)"
For example:
GuiUtils.pressTab(1); <------------- // add this method before popup show
int result = JOptionPane.showConfirmDialog(this, inputs, "Text search window", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION)
{
}
If you should press multiple times on "Tab" to get your Component you can use below method:
GUIUtils.pressTab(3);
Definition:
public static void pressTab(int amountOfClickes)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
Robot robot = new Robot();
int i = amountOfClickes;
while (i-- > 0)
{
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_TAB);
}
}
catch (AWTException e)
{
System.out.println("Failed to use Robot, got exception: " + e.getMessage());
}
}
});
}
If your Component location is dynamic, you can run over the while loop without limitation, but add some focus listener on the component, to stop the loop once arrived to it.