[英]Change Value of Custom JButton Click
我试图更改单击JOptionPane
的自定义JButton
的值,因为它的默认值为-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"};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.