import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.FileNotFoundException; import javax.swing.*; public class Test_17_6 extends JFrame{ private JPanel JP1 = new JPanel(); private JPanel JP2 = new JPanel(); private JLabel jl1 = new JLabel("Mile"); private JLabel jl2 = new JLabel("KiloMeter"); private JTextField jtf1 = new JTextField(10); private JTextField jtf2 = new JTextField(10); private Double distance; public Test_17_6(){ JP1.setLayout(new GridLayout(2,1)); jtf1.setHorizontalAlignment(JTextField.RIGHT); jtf2.setHorizontalAlignment(JTextField.RIGHT); JP1.add(jl1); JP1.add(jl2); JP2.setLayout(new GridLayout(2,1)); JP2.add(jtf1); JP2.add(jtf2); add(JP1,BorderLayout.CENTER); add(JP2,BorderLayout.EAST); //add listener jtf1.addKeyListener(new KeyAdapter(){ @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if(e.getKeyCode() == KeyEvent.VK_ENTER) { distance = 1.609344 * Double.parseDouble(jtf1.getText()); jtf2.setText(String.valueOf(distance)); } } }); jtf2.addKeyListener(new KeyAdapter(){ @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if(e.getKeyCode() == KeyEvent.VK_ENTER) { distance = Double.parseDouble(jtf2.getText()) / 1.609344; jtf1.setText(String.valueOf(distance)); } } }); } public static void main(String[] args) { // TODO Auto-generated method stub Test_17_6 frame = new Test_17_6(); frame.setTitle("Test_17_6"); frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
时间: 2024-12-05 21:26:50