我有以下代码,它是将摄氏温度转换为华氏温度的简单小程序。
如果输入正确的数字并单击按钮,则温度将被转换并显示没有问题。但是,如果文本框包含无效条目,则需要在错误面板上的标签上显示一条消息,但除非我调整小程序的大小,否则不会发生这种情况。所以问题是“如何重绘!!!”
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TemperatureConverter extends Applet{
private JLabel lblCel=new JLabel("Celsius Temperature :");
private JLabel lblFar=new JLabel("Fahrenheit value :");
private JLabel lblResult=new JLabel("");
private JLabel lblError=new JLabel("");
private JTextField txtFahr;
private JPanel celsPanel;
private JPanel farPanel;
private JPanel errorPanel;
private JButton btnEnter = new JButton("Convert");
public double temp = 0.0;
public void init(){
celsPanel = new JPanel(new GridLayout(1,3,2,2));
celsPanel.add(lblCel);
txtFahr = new JTextField(50);
celsPanel.add(txtFahr);
btnEnter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try{
temp = Double.parseDouble(txtFahr.getText());
double X = (temp - 32)* 0.69;
lblResult.setText(String.valueOf(X));
lblError.setText(" ");
}
catch(NumberFormatException ex){
lblError.setText("Invalid Celsius Value");
}
}
});
celsPanel.add(btnEnter);
farPanel = new JPanel(new GridLayout(1,2,2,2));
farPanel.add(lblFar);
lblResult.setSize(100, 30);
farPanel.add(lblResult);
errorPanel = new JPanel();
lblError.setSize(100, 30);
errorPanel.add(lblError);
setLayout(new GridLayout(3,2,2,2));
add(celsPanel);
add(farPanel);
add(errorPanel);
setSize(550,200);
}
}
任何人都可以解决这个问题吗?我在考虑标签尺寸问题,但后来我不确定。