【发布时间】:2018-02-06 11:04:38
【问题描述】:
我正在做一个简单的公斤到磅的转换器,我有一个文本字段,上面写着“这里的公斤”,当用户输入输入时,它会被附加,但不会被覆盖。请帮忙。
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UnitConvertKg {
JFrame f;
JPanel p;
JButton b1;
JTextField tf1,tf2;
UnitConvertKg(){
f=new JFrame("UnitConvertKg");
p=new JPanel();
tf1=new JTextField("Kg here");
//this is predefined text and I want that this gets overwritten when t //user types in kgs.
tf2=new JTextField(" ");
b1=new JButton("CONVERT");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
double d = Double.parseDouble(tf1.getText())*2.204;
tf2.setText(String.valueOf(d));
}
});
p.add(tf1);
p.add(tf2);
p.add(b1);
p.setForeground(Color.blue);
f.add(p);
f.setSize(400,400);
}
【问题讨论】:
-
您需要在字段中添加占位符而不是文本。见stackoverflow.com/questions/13033600/… 和stackoverflow.com/questions/16213836/…。希望它会有所帮助
-
JTextField 的占位符:-stackoverflow.com/questions/36070306/…
-
如果这不是重复的,请edit 您的问题包含一个minimal reproducible example,以显示您选择的方法。
标签: java swing jtextfield