Thread: Issue with Java

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    4
    Rep Power
    0

    Issue with Java


    Hi, i have a project that wants to make a program that calculates the temperature for Celsius to Fahrenheit and vice versa. I am using 2 jtextfields and when the user is writing a number to celsius textfield it auto calculates the farenheit with a documentlistener. How can i make the same thing happen with the farenheit at the same time ? Do i have to use another documentlistener ? I tryied to do so and it crashed.
    Here is my code so far :
    final BorderLayout f1 = new BorderLayout();
    JPanel mainPanel = new JPanel(new FlowLayout());
    mainPanel.add(new JLabel("Celsius"));
    final JTextField tx1 = new JTextField(7);
    mainPanel.add(tx1);
    final JTextField tx2 = new JTextField(7);
    mainPanel.add(tx2);
    mainPanel.add(new JLabel("Farenheit"));
    add(mainPanel,f1.CENTER);
    JButton kathbutton = new JButton("Clear");
    JPanel southPanel = new JPanel(new FlowLayout());
    southPanel.add(kathbutton);
    add(southPanel,f1.SOUTH);
    kathbutton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
    tx1.setText("");
    tx2.setText("");
    }
    });

    DocumentListener documentListener = new DocumentListener() {
    public void changedUpdate(DocumentEvent documentEvent) {

    }
    public void insertUpdate(DocumentEvent documentEvent) {
    printIt(documentEvent);
    }
    public void removeUpdate(DocumentEvent documentEvent) {
    printIt(documentEvent);
    }
    private void printIt(DocumentEvent documentEvent) {
    DocumentEvent.EventType type = documentEvent.getType();
    if (tx1.getText().isEmpty()==true){
    tx2.setText("");
    }
    else if (isInteger(tx1.getText())==false){
    if (tx1.getText().equals("-")){

    }
    else {
    JOptionPane.showMessageDialog(null, "Error");
    }
    }
    else{
    String far=tx1.getText();
    Double f = Double.parseDouble(far);
    Double x=9/5.0*f+32;
    int y = (int)Math.round(x);
    tx2.setText(""+y);
    }


    }
    };

    tx1.getDocument().addDocumentListener(documentListener);


    Please help
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,724
    Rep Power
    348
    Please edit your post and wrap your code with code tags:
    [code]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.

IMN logo majestic logo threadwatch logo seochat tools logo