我刚开始使用Swing进行编程。我正在使用Swing制作Fitness应用程序。我有两个问题:
JTextField
的限制设置为最多3位?这是我的代码。如果我在某个地方出错,请纠正我。建议我在哪里可以做出改进。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;//since obsolete
class H1 extends JFrame implements ActionListener
{
JLabel l1,l2,l3,l4,l5;
JTextField t1,t2,t3;
JRadioButton r1,r2;
ButtonGroup bg1;
JLabel bmr;
JLabel bmi;
int click=0;
JButton b1,b2;Container c1;
public static void main(String args[])
{
H1 j1 =new H1();
j1.setTitle("Personal Scales ");
j1.setSize(1000,1000);
j1.setVisible(true);
j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j1.pack();
}
H1()
{
c1=this.getContentPane();
setLayout(new BoxLayout(c1,BoxLayout.Y_AXIS));
JPanel j1 = new JPanel();
j1.setLayout(new FlowLayout());
t1 = new JTextField(10);
l1=new JLabel("Height");
j1.add(l1);
j1.add(t1);
c1.add(j1);
JPanel j2 = new JPanel();
j2.setLayout(new FlowLayout());
l2=new JLabel("Weight");
t2 = new JTextField(10);
j2.add(l2);
j2.add(t2);
c1.add(j2);
JPanel j3 = new JPanel();
j3.setLayout(new FlowLayout());
l3=new JLabel("Age");
t3 = new JTextField(10);
j3.add(l3);
j3.add(t3);
c1.add(j3);
JPanel j4 = new JPanel();
j4.setLayout(new FlowLayout());
l4=new JLabel("Sex");
bg1=new ButtonGroup();
r1=new JRadioButton("M");
r2=new JRadioButton("F");
bg1.add(r1);//button grouping is done to avoid multiple selection of radio button
bg1.add(r2);
j4.add(l4);
j4.add(r1);
j4.add(r2);
c1.add(j4);
JPanel j5 = new JPanel();
j5.setLayout(new FlowLayout());
b1=new JButton("Calculate Scales");//creating instance of JButton
j5.add(b1);
c1.add(j5);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
click +=1;
//JLabel bmr;
//JLabel bmi;
long ht=Long.parseLong(t1.getText());
long wt=Long.parseLong(t2.getText());
long age=Long.parseLong(t3.getText());
//JPanel j6 = new JPanel();
//j6.setLayout(new FlowLayout());
double bmi1 = wt/Math.pow((ht * 0.01),2);
String bmi2 = Double.toString(bmi1);//since double cant be added to container
bmi=new JLabel("BMI "+bmi2);
//c1.add(j6);
// JPanel j7 = new JPanel();
//j7.setLayout(new FlowLayout());
double bmr1;String bmr2;
if(r1.isSelected())
bmr1 = 66.47 +(13.75 * wt) + (5.003 * ht) - (6.775 * age);
else
bmr1 = 655.1 +(9.563 * wt) + (1.85 * ht) - (4.676 * age);
bmr2=Double.toString(bmr1);
bmr=new JLabel("BMR "+bmr2);
if(click>1)
{
c1.remove(bmi);
c1.remove(bmr);
}
/*j6.add(bmi);
j6.add(bmr);*/
c1.add(bmi);
c1.add(bmr);
}
}
答案 0 :(得分:1)
我也是java的新手,所以如果我错了,请纠正我,因此,我不能给你写评论并且必须写一个答案;)
正如我所看到的,每次单击按钮时都会创建一个新的JLabel
尝试使用例如。对于bmi.setText("BMI here" + bmi2);
的结果说明setText()
,您只需更改此标签中的文字。并且作为变量声明使用JLabel bmi = null;
也许您还可以添加JPanel来显示结果,以使JLabel成为固定位置并初始化它。
我希望我可以帮助你;)
Zorian