gpt4 book ai didi

java - 帮助在 JComboBox 中的 ItemChange 时自动更改值

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:50 25 4
gpt4 key购买 nike

我有一个程序,我在其中使用了 3 个东西,一个复选框、一个组合框和一个文本字段。如果启用复选框,则启用组合框和文本字段,除非启用,否则逻辑如下所示。

然后通过将它与组合框中的项目相乘,在文本字段中设置一些值。

The JFrame that I am working on

从框架来看 - Final Price 的值为 Price * Quantity。

现在,当我点击购买时,一切正常。但是,当我从 Jcombobox 更改值时,它不会自动更改最终价格的值,而是像第一种情况一样保持为 1200。对于要更改的值,我取消选中然后选中复选框。

可能是什么问题。我已将 ItemListner 用于复选框和组合框。

@Override
public void itemStateChanged(ItemEvent e){

Object get = e.getSource();

int multiplier;
int ftotal;


if (e.getStateChange()==ItemEvent.SELECTED){
if(get==chkbox1){
qntbox1.setEnabled(true);
size1.setEnabled(true);
multiplier = Integer.parseInt(String.valueOf(qntbox1.getSelectedItem()));


ftotal = Integer.parseInt(price1.getText()) * multiplier;
fprice1.setText(String.valueOf(ftotal));}

最佳答案

您必须为您的 JComboBox 实现 ActionListener:

private static final String command_cbo1 = "ComboBox1";
// ...

public class YourClass implements ItemListener, ActionListener
{
// ...

public YourClass()
{
// ...
qntbox1.addActionListener(this);
qntbox1.setActionCommand(command_cbo1);
// ...
}

// ...

public void itemStateChanged(ItemEvent e)
{
// ...
}

// ...

public void actionPerformed(ActionEvent e)
{
JComboBox cb = (JComboBox) e.getSource();
String s = (String) cb.getSelectedItem();

if(e.getActionCommand().equals(command_cbo1))
{
fprice1.setText("" + (Integer.parseInt(price1.getText()) * Integer.parseInt(s)));
}
// ...
}

// ...
}

关于java - 帮助在 JComboBox 中的 ItemChange 时自动更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970798/

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