请教高人:
编写成人标准身高和体重互查程序。身高和体重在两个不同的文本框中输入,要求输入一个,输出另一个。用一个按钮启动互查。
互查公式为: 体重=身高-100
我编写的程序如下:可是输入体重就会出现问题是怎么回事啊!!!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class HeightWeight implements ActionListener
{
JTextField tf1=new JTextField(10);
JTextField tf2=new JTextField(10);
HeightWeight()
{
GUI();
}
void GUI()
{
JFrame myframe=new JFrame("身高与体重查询");
myframe.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JLabel label1=new JLabel("身高");
JLabel label2=new JLabel("体重");
//JTextField tf1=new JTextField(10);
tf1=new JTextField(10);
//JTextField tf2=new JTextField(10);
tf2=new JTextField(10);
JButton button=new JButton("转换");
button.addActionListener(this);
p1.add(label1);
p1.add(tf1);
p2.add(label2);
p2.add(tf2);
p3.add(button);
myframe.getContentPane().add(p1);
myframe.getContentPane().add(p2);
myframe.getContentPane().add(p3);
myframe.setSize(200,300);
myframe.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String t=tf1.getText().toString();
int x=Integer.parseInt(t);
Integer h=x-100;
String u=Integer.toString(h);
tf2.setText(u);
String s=tf2.getText().toString();
int y=Integer.parseInt(s);
Integer l=y+100;
String v=Integer.toString(l);
tf1.setText(v);
}
public static void main(String[] args)
{
new HeightWeight();
}
}
------解决方案--------------------
- Java code
import java.awt.*;import javax.swing.*;import java.awt.event.*;public class HeightWeight implements ActionListener{ JTextField tf1=new JTextField(10); JTextField tf2=new JTextField(10); HeightWeight() { GUI(); } public void GUI() { JFrame myframe=new JFrame("身高与体重查询"); myframe.setLayout(new FlowLayout(FlowLayout.CENTER)); JPanel p1=new JPanel(); JPanel p2=new JPanel(); JPanel p3=new JPanel(); JLabel label1=new JLabel("身高"); JLabel label2=new JLabel("体重");//JTextField tf1=new JTextField(10); tf1=new JTextField(10);//JTextField tf2=new JTextField(10); tf2=new JTextField(10); JButton button=new JButton("转换"); button.addActionListener(this); p1.add(label1); p1.add(tf1); p2.add(label2); p2.add(tf2); p3.add(button); myframe.getContentPane().add(p1); myframe.getContentPane().add(p2); myframe.getContentPane().add(p3); myframe.setSize(200,300); myframe.setVisible(true); myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { String t=tf1.getText().trim(); if(!t.isEmpty()){ int x=Integer.parseInt(t); Integer h=x-100; String u=Integer.toString(h); tf2.setText(u); } String s=tf2.getText().trim(); if(!s.isEmpty()){ int y=Integer.parseInt(s); Integer l=y+100; String v=Integer.toString(l); tf1.setText(v); } } public static void main(String[] args) { new HeightWeight(); }}