首页 > 解决方案 > 更改自定义 JButton 单击的值

问题描述

我正在尝试更改单击自定义项的值,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");
        }

    }


}

标签: javaswingjframejbuttonjoptionpane

解决方案


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

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

推荐阅读