我有以下代码,这是一个简单的小程序,可以将摄氏度转换为华氏度。
如果输入了正确的数字并单击了按钮,则温度将转换并显示无问题。但是,如果文本框包含无效条目,则需要在错误窗格的标签上显示消息,但除非调整小程序的大小,否则不会发生这种情况。所以问题是“如何重新粉刷!!!”

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);

}

}

有人能搞清楚吗?我在想一个标签尺寸的问题,但我不确定。

最佳答案

试试这个:

    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(" ");
                this.repaint();
            }
            catch(NumberFormatException ex){
                lblError.setText("Invalid Celsius Value");
            }
        }
    });

08-27 14:19