Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repaint Java Applet

I have the following code that is a simple Applet that converts Celsius to Fahrenheit.

If a correct number is entered and the button is clicked, the temperature is converted and displayed no issues. However, if the text box contains an invalid entry a message needs to show up on a label on the error pannel but this doesn't happen unless I resize the applet. So the question is "How to repaint!!!"

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

}

}

Can anyone figure this out? i was thinking of a label size issue, but then I'm not sure about that.

like image 412
joe Avatar asked Feb 23 '26 01:02

joe


1 Answers

try this :

    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");
            }
        }
    });
like image 166
Mehdi Karamosly Avatar answered Feb 24 '26 14:02

Mehdi Karamosly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!