gpt4 book ai didi

java - 英里到公里转换器(事件驱动)

转载 作者:行者123 更新时间:2023-11-29 03:31:41 26 4
gpt4 key购买 nike

我需要创建一个显示MilesKilometersJPanel。当您将数字输入其中一个时,它会使用 Enter 键将其转换为另一个。

我不知道如何正确获取 KeyListener 来执行转换。我不是在寻找答案,只是在寻找一些指导或指向类似示例的链接。谢谢。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;

import javax.swing.*;

public class Ch09Asg extends JFrame {
private JTextField jtfMiles = new JTextField(10);
private JTextField jtfKilo = new JTextField(10);

public Ch09Asg() {
JPanel p1 = new JPanel(new GridLayout(2,2));
p1.setSize(400,250);
p1.add(new JLabel("Mile"));
p1.add(jtfMiles);
p1.add(new JLabel("Kilometers"));
p1.add(jtfKilo);
jtfMiles.setHorizontalAlignment(JTextField.RIGHT);
jtfKilo.setHorizontalAlignment(JTextField.RIGHT);

add(p1, BorderLayout.CENTER);

jtfMiles.addActionListener(new ButtonListener(){
});

jtfKilo.addActionListener(new ButtonListener(){
});
}

class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//double mi = convertKmtoMi
//Double.parseDouble(jtfMiles.getText());
//double kilom =
//Double.parseDouble(jtfKilo.getText());
//---------------------------------------KILOTOMILE

String kmStr = jtfKilo.getText(); //Note 3
double km = Double.parseDouble(kmStr);

//... Convert it
double mi = convertKmToMi(km); //Note 4

//... Convert it to a string and set mi textfield
jtfMiles.setText("" + mi);

//--------------------------------------MILESTOKILO
String miStr = jtfMiles.getText(); //Note 3
double mi2 = Double.parseDouble(miStr);

//... Convert it
double km2 = convertKmToMi(mi2); //Note 4

//... Convert it to a string and set mi textfield
jtfMiles.setText("" + km2);
}
}

public static double convertKmToMi(double kilometers) {
// Assume there are 0.621 miles in a kilometer.
double miles = kilometers * 0.621;
return miles;
}

public static double convertMitoKm(double miles) {
// Assume there are 0.621 miles in a kilometer.
double kilometers = miles / 0.621;
return kilometers;
}

public static void main(String[] args) {
Ch09Asg frame = new Ch09Asg();
frame.pack();
frame.setTitle("Mile/Kilometer Converter");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

最佳答案

您应该添加 ActionListener,而不是将 KeyListeners 添加到文本字段,这实际上并不能很好地工作一个按钮的 Action 监听器。当您按下回车键时,它们会被激活。

关于java - 英里到公里转换器(事件驱动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17846876/

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