【发布时间】:2018-09-27 21:15:26
【问题描述】:
我正在尝试更改在我的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");
}
}
}
【问题讨论】:
-
你的按钮已经有了不同的行为。例如,如果在第 21 行删除
frame.dispose();,Button 不会关闭程序,但右上角的退出按钮会。
标签: java swing jframe jbutton joptionpane