更改自定义JButton单击的值

时间:2018-09-27 21:15:26

标签: java swing jframe jbutton joptionpane

我试图更改单击JButton中的自定义JOptionPane的值,因为它的默认值为-1,与单击右上角的退出按钮的值相同。根据单击JButton还是单击退出按钮,我想有不同的行为。这是我的代码示例。我该怎么办?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Example {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(1, 2));

        JButton b1 = new JButton("Find nth Fib");
        JTextField n = new JTextField();

        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String output = n.getText();
                frame.dispose();
                //reference to external method with String output as arg
            }
        });

        panel.add(b1);
        panel.add(n);

        Object[] options = {"Quit"};

        int pos = JOptionPane.showOptionDialog(frame, panel, 
                "Enter a number", JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION, null, options, null);

        if (pos == 0 || pos == -1) { //check if quit button or X button are pressed
            frame.dispose();
            System.out.println("exit button pressed");
        }

    }


}

1 个答案:

答案 0 :(得分:0)

  

将按钮添加为选项(不是面板的一部分):

Object[] options = {"Find nth Fib", "Quit"};