簡體   English   中英

如何在If語句中使用JOptionPane?

[英]How do I use JOptionPane in an If statement?

我是學習Java的新手。 在一個作業中,我正在使用If / Else語句並嘗試在JOptionPane中顯示信息。 這是我制作的一個簡單示例,用來說明我遇到的問題。 如果字符串hello中的輸入等於“ hey”,我想顯示“ Hello there”。

什么都沒發生。

我注意到,如果將JOptionPane語句放在代碼的前面,例如在掃描程序聲明旁邊,它將起作用。 另外,如果我這樣做並且將另一個JOptionPane保留在原始位置,則將出現兩個對話框。

我當時在想,也許掃描儀的輸入正以某種方式弄亂了它。

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();
    }
}

有誰知道為什么對話框沒有顯示? 謝謝!

我相信您在這里沒有任何問題,只是您的JOptionPane隱藏在IDE窗口后面或后面。 為了始終將其放在最前面,請嘗試使用如下所示的內容:

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

這將使您在使其可見的位置更具靈活性。 另一種方法是較短的但相同的想法:

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

完整的代碼供您使用:

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");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM