如何将按钮和actionlisteners添加到Java Swing中附加的JoptionPane?

时间:2013-11-20 04:54:27

标签: java swing button joptionpane

以下是包含两个JoptionPane的简单代码。 目前,它没有按钮,但是我想将按钮附加到第二个JOptionPane以获取是或否事件。 此外,当两个JOptionPanes关闭时,Frame不会关闭。当Frame关闭时,有办法强制关闭JoptionPanes

这是我当前的代码

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class TestJoption {

    public static void main(String[] args){

        JFrame frame = new JFrame("Game");

        JOptionPane.showMessageDialog(frame, "You Won!", "Winner", JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(frame, "yes No", "play again", JOptionPane.INFORMATION_MESSAGE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }
}

3 个答案:

答案 0 :(得分:3)

你可以这样做:

JOptionPane.showConfirmDialog(frame, "yes No", "play again", JOptionPane.YES_NO_OPTION);

弹出包含yes和no选项的方框..

答案 1 :(得分:1)

我认为你需要下一个代码:

    JOptionPane.showMessageDialog(frame, "You Won!", "Winner", JOptionPane.INFORMATION_MESSAGE);
    int result = JOptionPane.showConfirmDialog(frame, "yes No", "play again",JOptionPane.YES_NO_OPTION);
    if(result == JOptionPane.NO_OPTION){
        frame.dispose();
    }

另请阅读dialogs的教程。

答案 2 :(得分:0)

关闭窗口,您可以使用

frame.setVisible(false);

或者您只需致电

System.exit(0);

这将终止您的流程。