java - 更改自定义 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");
}
}
}
解决方案
添加按钮作为选项(不是面板的一部分):
Object[] options = {"Find nth Fib", "Quit"};
推荐阅读
- spring - Spring Boot 依赖
- c++ - 打印系列时循环出现问题
- amazon-web-services - 数据管道和 EMR 错误:未找到默认 VPC。但我无权创建默认 VPC
- node.js - 为什么将 Angular 项目部署到 Heroku 时出现 ng not found 错误?
- laravel - VScode 无法将文件保存在我的 WSL2 主文件夹中
- php - OctoberCMS Responsiv Uploader Plugin,文件有空值
- python-3.x - 路径、安装包、Conda 环境和几个内置命令的问题
- python - 检查簿记员中的双打
- php - Composer 总是安装最新版本,如果包版本用逻辑 OR 分隔
- python - 从列表中获取元素的所有组合,包括所有不同的顺序并以 2 种不同的方式编写