简体   繁体   中英

How do I use JOptionPane in an If statement?

I am new to learning Java. In an assignment, I am using If/Else statements and trying to display information in JOptionPane. Here is a quick example I made to show the issue I'm having. I want to display "Hello there" if the input in the string hello is equal to "hey".

Nothing comes up.

I noticed that if I put the JOptionPane statement earlier in the code, such as next to the scanner declaration, it will work. Also, if I do that AND leave the other JOptionPane in the original location, there will be TWO dialog boxes.

I was thinking that maybe the scanner input is messing with it somehow.

import javax.swing.JOptionPane; 
import java.util.Scanner;

public class HW2 {
    public static void main( String args[] ) {
        Scanner kb = new Scanner(System.in);
        System.out.print("Say hey");
        String hello = kb.nextLine();
        if (hello.equals("hey")) 
            JOptionPane.showMessageDialog(null, "Hello there!");
        kb.close();
    }
}

Does anyone know why the dialog box isn't showing up? Thanks!

I believe you don't really have any problem here, simply your JOptionPane is hidden behind your IDE window or is somewhere in the back. In order to always bring it to front, try using something like this:

if (hello.equals("hey")) {
     JOptionPane pane = new JOptionPane();
     JDialog dialog = pane.createDialog("My Test");
     pane.setMessage("Hello There");
     dialog.setAlwaysOnTop(true);
     dialog.setVisible(true);
}

This will give you a bit more flexibility in where you want to make it visible. Another way a bit shorter, but same idea:

if (hello.equals("hey")) {
    JDialog dialog = new JDialog();
    dialog.setAlwaysOnTop(true);
    JOptionPane.showMessageDialog(dialog, "Hello There");
}

Complete code for you to play around with:

import javax.swing.*;
import java.util.Scanner;

public class HW2 {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        System.out.println("Say hey");
        String hello = kb.nextLine(); //use kb.nextLine().trim() if you dont want whitespaces
        if (hello.equals("hey")) {
            JDialog dialog = new JDialog();
            dialog.setAlwaysOnTop(true);
            JOptionPane.showMessageDialog(dialog, "Hello There");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM