gpt4 book ai didi

java - JOptionPane 自定义 JButton 选择后未关闭

转载 作者:行者123 更新时间:2023-12-02 03:58:44 25 4
gpt4 key购买 nike

我有一个财务程序,在选择股票并选择价格和数量后,我们在 joptionpane 面板上有两个选项“购买”和“取消”。在我的一生中,我无法让它发挥作用。任何帮助将不胜感激。谢谢。我将 int buyNow 作为构造函数中的一个字段。

final JButton buy = new JButton("Buy");
buy.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent evt)
{
buyStock();
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
double doubleBal = sql.getBalance().doubleValue();
String bal = nf.format(doubleBal);
jLabel_DisplayBalance.setText(bal);
double doubleCash = sql.getCash().doubleValue();
String cash = nf.format(doubleCash);
jLabel_DisplayCash.setText(cash);
double doubleStock = sql.getStock().doubleValue();
String stock = nf.format(doubleStock);
jLabel_DisplayStock.setText(stock);
System.out.println(buyNow);
}
});
final JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent evt)
{
System.out.println(buyNow);
}
});
JButton[] buttons = {buy, cancel};
buyNow = JOptionPane.showOptionDialog(rootPane, getBuyOrSellPanel ("Buy"), title,
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, buttons, cancel);

我正在使用 system.out.println 进行测试,看看它是否为所选按钮获取了正确的 int 值,但它只为两个按钮显示 0。我不知道为什么。

最佳答案

不要传入 JButton 数组,而是传入 String 数组。请注意,您的取消和购买 ActionListener 也不起作用,也没有必要。相反,测试返回到 buyNow 变量的 int 数组索引。在 if block 内(使用 equals 方法测试),采取相应的行动。

int buyNow = -1;
String[] options = {"Buy", "Cancel"};
buyNow = JOptionPane.showOptionDialog(rootPane, getBuyOrSellPanel ("Buy"), title,
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, cancel);

if ("Buy".equals(options[buyNow])) {
// code for "Buy" option
} else if ("Cancel".equals(options[buyNow])) {
// code for "cancel" option
}

关于java - JOptionPane 自定义 JButton 选择后未关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com