我需要创建一个JPanel
显示Miles和Kilometers的。当您将数字输入一个时,它会使用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);
}
}