gpt4 book ai didi

java - 如何在单击另一个 Jbutton 时更改 Jbutton 的功能?

转载 作者:太空宇宙 更新时间:2023-11-04 14:03:47 25 4
gpt4 key购买 nike

我正在编写一个程序,它将以磅为单位的重量转换为公斤,并将以公斤为单位的重量转换为磅。输出窗口如下:

enter image description here

当我想将公斤转换为磅时,我单击切换按钮,输出更改如下:

enter image description here

但问题是,当我单击“转换”时,它仍然将重量转换为千克而不是磅。

我希望在单击“切换”按钮时更改“转换”按钮的功能,以便将重量(公斤)转换为磅。请帮忙。

我的源代码如下:

public class convertApp extends JFrame implements ActionListener {
private JLabel poundlbl = new JLabel("Weight in Pounds");
private JLabel kglbl = new JLabel("Weight in Kilograms");

private JTextField poundbx= new JTextField(12);
private JTextField kgbx= new JTextField(12);

private JButton conbtn=new JButton("Convert");
private JButton switchbtn=new JButton("Switch");
private JButton newconbtn=new JButton("Convert");
private JPanel bxPanel = new JPanel();

public convertApp(){
super("Weight Converter");
bxPanel.setLayout(new GridLayout(5,29,5,5));
bxPanel.add(poundlbl);
bxPanel.add(poundbx);
bxPanel.add(kglbl);
bxPanel.add(kgbx);
bxPanel.add(conbtn);
bxPanel.add(switchbtn);

//bxPanel.setBackground(Color.gray);



this.setLayout(new GridLayout(1,1,0,0));
this.add(bxPanel);



this.setVisible(true);
//what to do if i close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put window in the center
this.setLocationRelativeTo(null);
//disable resize
this.setResizable(false);
//pack all the components within the window
this.pack();

conbtn.addActionListener(this);
switchbtn.addActionListener(this);


}

public void actionPerformed(ActionEvent evnt){
if(evnt.getSource()==conbtn){
String poundtext = poundbx.getText();
int pound = Integer.parseInt(poundtext);

double kilo = pound * 0.453592;

kgbx.setText(""+kilo);
}

else if(evnt.getSource()==switchbtn)
{
poundlbl.setText("Weight in Kilograms:");
kglbl.setText("Weight in Pounds:");

if(evnt.getSource()==conbtn){
String kilotext = poundbx.getText();
int kilo = Integer.parseInt(kilotext);

double pound = kilo * 2.20462;

kgbx.setText(""+pound);
}

}


}

}

最佳答案

创建 boolean 变量

boolean switch=true;

void kiloGramToPound{
//Convert Codes Here
}

void PoundToKiloGram{
//Convert Codes Here
}

转换按钮操作已执行

if(switch==true){
kiloGramToPound();
}else{
PoundToKiloGram();
}

切换按钮操作已执行

if(switch==true){
switch=false;
}else{
switch=true;
}

关于java - 如何在单击另一个 Jbutton 时更改 Jbutton 的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29058398/

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