DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 12 of 12

Thread: Problem figuring out how to use KeyListener

Hybrid View

  1. #1
    Join Date
    May 2006
    Posts
    4

    Problem figuring out how to use KeyListener

    I am trying to create a Celsius Converter GUI using KeyListener to get information from the user and then processing it afterwards but I can't seem to get it to work and I need help. Below is the code I have so far and I would appreciate it if anyone could help me get this problem fixed.

    Java NewBie


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class CelsiusCalculator extends JFrame implements KeyListener
    {
    JTextField fahTextField;
    JLabel celsLabel, fahLabel,displayCelsius;
    JButton convert;
    //KeyListener Listener;
    //---------------------------------------------------------------------------------------------------------
    //Constructor
    public CelsiusCalculator()
    {
    super("Fahrenheit To Celsius Calculator");
    FlowLayout placer=new FlowLayout(FlowLayout.LEFT);
    setLayout(placer);
    fahLabel = new JLabel ("Enter FahrenHeight Value: ");//Label for Fahrenheit
    add(fahLabel);
    //Create a text box of size 10
    fahTextField = new JTextField(10);//Textbox to get Fahrenheit input
    add(fahTextField);
    celsLabel = new JLabel ("Celsius: ");//Label to display the CELSIUS
    add(celsLabel);
    displayCelsius = new JLabel ("");//Label to Output result in
    add(displayCelsius);
    convert = new JButton("Convert");
    add(convert);
    convert.addKeyListener(this);//allow frame to process key events
    setVisible(true);
    }// End Constructor

    //------------------------------------------------------------------------------------------------------------
    //implementation of KeyListener methods
    public void keyPressed(KeyEvent e)
    {
    CalcCelsius(e);
    }
    public void keyReleased(KeyEvent e)
    {
    CalcCelsius(e);
    }
    public void keyTyped(KeyEvent e)
    {
    CalcCelsius(e);
    }
    //calculation using the information provided by user
    public void CalcCelsius (KeyEvent e)
    {
    int temp = (int)((Double.parseDouble(e.getKeyText(e.getKeyCode()))-32)*0.56);
    displayCelsius.setText(temp+" Degrees");
    }// CalcCelsius
    //-----------------------------------------------------------------------------------------------------------------
    // private static void ShowConverter() {
    //Make sure we have nice window decorations.
    // JFrame.setDefaultLookAndFeelDecorated(true);
    // CelsiusCalculator celsium = new CelsiusCalculator(); }
    public static void main(String[] args)
    { //listen to events from the fahTextField
    JFrame.setDefaultLookAndFeelDecorated(true);
    CelsiusCalculator celsium = new CelsiusCalculator();
    }

    }//End of Class

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    What happens when you try to compile it? What error messages are you seeing?

    KeyListener is a little tough for a text field, because every time you push a key you are generating an event, and you have your program coded to try to convert the value in the text field with every key press. If I were writing this I would use an ActionListener tied to the Convert JButton [but I don't know the requirements you are writing under].

  3. #3
    Join Date
    May 2006
    Posts
    4
    When I compiled it, I got no errors whatsoever. I also go none when I built it and when I execute, I get no errors when I use JCREATOR. So I am kind of stuck as I do not know what to do next.

    This is the exercise I am trying to solve.....

    1) Write a temperature conversion application that converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from the keyboard (via JTextField). A JLabel should be used to display the converted temperature. Use the following formula for the conversion:

    Celsius = 5/9(Fahrenheit -32)

  4. #4
    Join Date
    Mar 2006
    Posts
    35
    Here's one way to do it just look at the highlighted areas the rest is netbeans generated code hope it helps some. It might seem a little confusing at first because I didn't take a lot of time to name the objects but keep looking you'll figure it out.

    import java.awt.HeadlessException;
    import java.awt.event.KeyEvent;
    /*
    * celcius.java
    *
    * Created on May 3, 2006, 11:39 PM
    */

    /**
    *
    * @author Compaq_Owner
    */
    public class celcius extends javax.swing.JFrame {
    double temp1=0;
    /** Creates new form celcius */
    public celcius() {
    initComponents();
    }

    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jLabel2 = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();

    jLabel2.setText("jLabel2");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory .createLineBorder(new java.awt.Color(0, 0, 0)), null));

    jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jTextField1KeyTyped(evt);
    }
    });

    jButton1.setText("Convert");

    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    jLabel3.setText("Farenheight");

    jLabel4.setText("Celcuis");

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(30, 30, 30)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
    .add(jButton1)
    .add(24, 24, 24))
    .add(layout.createSequentialGroup()
    .add(10, 10, 10)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField1)
    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE))
    .addContainerGap(143, Short.MAX_VALUE))))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
    .add(109, 109, 109)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jLabel3))
    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 95, Short.MAX_VALUE)
    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jLabel4))
    .add(13, 13, 13)
    .add(jButton1)
    .add(24, 24, 24))
    );
    pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String temp = jTextField1.getText();

    try {
    temp1 = Double.parseDouble(temp);

    } catch (NumberFormatException ex) {
    ex.printStackTrace();


    } catch (HeadlessException ex) {
    ex.printStackTrace();



    }
    double celcuis = 5.0/9.0 * (temp1 - 32);
    jLabel1.setText( "" + celcuis);
    }

    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
    // TODOCelsiusCalculator add your handling code here:
    char c = evt.getKeyChar();
    if (!((Character.isDigit(c) ||
    (c == KeyEvent.VK_BACK_SPACE) ||
    (c == KeyEvent.VK_DELETE)))){
    getToolkit().beep();
    evt.consume();
    }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new celcius().setVisible(true);
    }
    });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

    }
    Last edited by blastmaster; 05-04-2006 at 01:49 AM.

  5. #5
    Join Date
    Mar 2004
    Posts
    635
    Well whats not working right? Getting the wrong output? No output at all? Be specific. I'm tired of people posting homework assignments then say fix it it's broken. Oh, and please use code tags in the future, everyone.

    As nspils suggested, using a JButton and ActionListener is probably easier and I would also guess it's how your teacher would prefer.

    Though I don't agree with the method definition you chose for "CalcCelsius (KeyEvent e)" I'll just skip that and move on to what I assume is the problem, since you didn't specifically state it. getKeyText() will only ever return 1 key, and so only the last key typed will ever be included in the equation that outputs the answer. Program will probably work, as long as the user only ever wants to convert a single digit. So if the user types 42, the output will reflect "2" as being the only input. Also, if you're going to let the whole Frame accept key events, you should set the text in a field somewhere so the user knows what input being calculated. It wont happen automatically if the textfield doesn't have the focus. You should add the key listener to the text field only. A problem does arise if you parse the text from the field instead of a single keyevent. I believe the keyevent is triggered before the typed character displays into the textfield. Thus, when your keyTyped() method calls your calculation method which then gets the text field's text, it wont have the latest character that was typed included; it'll always return 1 character less.

    user types "1"
    key event occurs
    do calculation; get text from field, which is nothing at this point
    text field updates value to reflect "1" was typed
    user types "2"
    key event occurs
    do calculation; get text from field, which now has "1"
    text field updates value to reflect "2" was typed and so now shows "12"

    This happened to me the other day, which is why I'm explaining it. I haven't looked into the problem in detail yet, so I'm not sure if I saw this happen as a mistake I made or not. But I figured I'd point it out to you incase you see the same thing, then you might know why.

  6. #6
    Join Date
    Feb 2006
    Location
    Cologne - Germany
    Posts
    271
    the problem with your code, rection, is that you write:
    Code:
     convert = new JButton("Convert");
    add(convert);
    convert.addKeyListener(this);//allow frame to process key events
    that means the key presses are ONLY registered when the user focuses on the button and presses keys.
    you will have to set the focus on the button with something like converter.requestFocus();
    but then, you will have the problem, that with
    Code:
     public void keyPressed(KeyEvent e)
    {
    CalcCelsius(e);
    }
    public void keyReleased(KeyEvent e)
    {
    CalcCelsius(e);
    }
    public void keyTyped(KeyEvent e)
    {
    CalcCelsius(e);
    }
    calccelsius will be invoked three times when a button is pressed: on button down, on button up and at all.
    you should just use the keyTyped (invoked when button generraly was typed)
    for the focus problem i suggest you to add the keylistener to a bigger and super component, like your frame:
    Code:
    public CelsiusCalculator()
    {
    ....
    super.addKeylistener(....)
    ....
    }
    this should capture the keys from everywhere.

  7. #7
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Does this problem call for a KeyListener? I don't see it.

  8. #8
    Join Date
    Mar 2006
    Posts
    35
    Here you go this is everything you need you probably will want to add a different layout manager to this to make it look better but the nuts and bolts are solid. I just used KeyListener for validation purposes I guess you don't have to use it I'm not sure I always try to add at least basic validation to any program I write.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class celcuis extends JFrame implements ActionListener, KeyListener {
    double temp1 = 0;
    JTextField FahTextField;
    JButton convert;
    JLabel celLabel;
    public celcuis()
    {

    super("Celcuis Converter");
    setLayout(new FlowLayout() );
    FahTextField = new JTextField(10);
    add(FahTextField);
    FahTextField.setText("0");
    FahTextField.addKeyListener(this);
    celLabel = new JLabel("Celcuis");
    add(celLabel);
    convert = new JButton("Convert");
    add(convert);
    convert.addActionListener(this);

    }

    public void keyTyped(KeyEvent e) {

    char c = e.getKeyChar();
    if (!((Character.isDigit(c) ||
    (c == KeyEvent.VK_BACK_SPACE) ||
    (c == KeyEvent.VK_DELETE)))){
    getToolkit().beep();
    e.consume();
    } }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {

    }

    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {

    }


    public void actionPerformed(ActionEvent e) {
    String temp = FahTextField.getText();

    try {
    temp1 = Double.parseDouble(temp);

    } catch (NumberFormatException ex) {
    ex.printStackTrace();


    } catch (HeadlessException ex) {
    ex.printStackTrace();



    }
    double celcuis = 5.0/9.0 * (temp1 - 32);
    celLabel.setText( "" + celcuis);
    }



    }// end class celcuis

  9. #9
    Join Date
    May 2006
    Posts
    4
    You guys have really helped me a lot. Using the code you provided, I was able to make the necessary changes I needed to the KeyListener and Buttons I already had and it works like magic now. I had so many exceptions even though it worked .... But I noticed that I did not have an ActionListener method and an exception thingy( I am yet to deal with those) in my program. But I am so very grateful for all the help and I look forward to learning more JAVA programming with your help.. thank you!!

  10. #10
    Join Date
    Mar 2006
    Posts
    35
    Here's one more tip, seperate your main method from your classes like this. This will go with the program code above


    import javax.swing.JFrame;
    public class fahconverter
    {
    public static void main(String args[])
    {
    celcuis calculate = new celcuis();
    calculate.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    calculate.setSize(200, 200);
    calculate.setVisible(true);

    }
    }

    You really need to get a firm understanding of GUI elements you program GUI didn't even show up when I compiled and ran it. Keep it up it gets easier the best way to learn from my experience is a combination of your text online tutorials and the most important thing is writing as many different type of small programs you can then build on them when you learn more.

  11. #11
    Join Date
    Apr 2006
    Posts
    28
    //Here your program, just improve a liitte bit

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class CelsiusCalculator extends JFrame implements KeyListener
    {
    JTextField fahTextField,celTextField;
    JLabel celsLabel, fahLabel,displayCelsius;
    JButton convert;
    //KeyListener Listener;
    //---------------------------------------------------------------------------------------------------------
    //Constructor
    public CelsiusCalculator()
    {
    super("Fahrenheit To Celsius Calculator");
    JPanel placer=new JPanel();
    placer.setLayout(new GridLayout(3,2,5,5));
    fahLabel = new JLabel ("Enter FahrenHeight Value: ");//Label for Fahrenheit
    placer.add(fahLabel);
    //Create a text box of size 10
    fahTextField = new JTextField(10);//Textbox to get Fahrenheit input
    placer.add(fahTextField);
    celsLabel = new JLabel ("Celsius: ");//Label to display the CELSIUS
    placer.add(celsLabel);
    //displayCelsius = new JLabel ("");//Label to Output result in
    //placer.add(displayCelsius);
    celTextField = new JTextField(10);//Textbox to display Celcisus output
    celTextField.setEnabled(false);
    celTextField.setHorizontalAlignment(JTextField.RIGHT);
    celTextField.setBackground(Color.WHITE);
    placer.add(celTextField);
    convert = new JButton("Convert");
    placer.add(convert);

    convert.addKeyListener(this);//allow frame to process key events
    Container c =getContentPane();
    c.add(placer,BorderLayout.CENTER);
    //getContentPane().add(placer,BorderLayout.CENTER);
    convert.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    int temp = (int)((Double.parseDouble(fahTextField.getText())-32)*0.56);
    celTextField.setText(temp+" Degrees");
    }

    });
    fahTextField.addKeyListener(new KeyAdapter()
    {
    public void keyReleased(KeyEvent ke)
    {

    try
    {
    int temp = Integer.parseInt(fahTextField.getText());

    }
    catch(NumberFormatException ne)
    {
    JOptionPane.showMessageDialog(null,ne.getMessage());
    }
    }
    });
    setSize(300,150);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }// End Constructor

    //------------------------------------------------------------------------------------------------------------
    //implementation of KeyListener methods
    public void keyPressed(KeyEvent e)
    {
    //CalcCelsius(e);
    }
    public void keyReleased(KeyEvent e)
    {
    //CalcCelsius(e);
    }
    public void keyTyped(KeyEvent e)
    {
    //CalcCelsius(e);
    }

    //-----------------------------------------------------------------------------------------------------------------
    // private static void ShowConverter() {
    //Make sure we have nice window decorations.
    // JFrame.setDefaultLookAndFeelDecorated(true);
    // CelsiusCalculator celsium = new CelsiusCalculator(); }
    public static void main(String[] args)
    { //listen to events from the fahTextField
    JFrame.setDefaultLookAndFeelDecorated(true);
    CelsiusCalculator celsium = new CelsiusCalculator();
    }

    }//End of Class

  12. #12
    Join Date
    May 2006
    Posts
    5
    Following the spec that you gave, this is probably who I'd do the F-C converter. Hitting ENTER on the JTextField sends the answer to the JLabel.

    Code:
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    /*
     * Write a temperature conversion application that converts from Fahrenheit to
     * Celsius. The Fahrenheit temperature should be entered from the keyboard (via
     * JTextField). A JLabel should be used to display the converted temperature.
     * Use the following formula for the conversion: Celsius = 5/9(Fahrenheit -32)
     */
    public class MyCelsius {
    
    	public static void main(String[] args) {
    		MyFrame frame = new MyFrame();		
    	}	
    }
    
    class MyFrame extends JFrame {
    	public MyFrame() {
    		super("Fahrenheit to Celsius Converter");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(300, 100);
    		setLocation(300, 200);		
    		add(new InputPanel());		
    		setVisible(true);
    	}
    }
    
    class InputPanel extends JPanel {
    	JLabel answerLabel;
    	JLabel inputLabel;
    	JTextField inputField;
    		
    	public InputPanel() {
    		setBackground(Color.yellow);
    		inputLabel = new JLabel("Enter Fahrenheit degrees: ");
    		add(inputLabel);
    		inputField = new JTextField(10);
    		inputField.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent evt) {
    				try {
    					answerLabel.setText("Fahrenheit: "+inputField.getText()+"   Celsius: "+convert(inputField.getText()));
    				} catch(NumberFormatException nfe) {
    					answerLabel.setText("Your entry is a mess. Try again!");
    				}				
    				inputField.setText("");
    			}
    		});
    		add(inputField);
    		answerLabel = new JLabel();
    		
    		add(answerLabel);
    	}
    	private String convert(String inputStr) throws NumberFormatException {
    		Double d = (.567)*(Double.parseDouble(inputStr)-32);		
    		return String.format("%,.2f",d);
    	}
    }
    Last edited by arowberry; 05-06-2006 at 02:09 AM.

Similar Threads

  1. Problem with Search
    By Irina in forum ASP.NET
    Replies: 0
    Last Post: 11-29-2002, 11:47 PM
  2. Replies: 0
    Last Post: 12-13-2001, 01:06 PM
  3. a problem with font and language
    By Roseta in forum VB Classic
    Replies: 0
    Last Post: 11-14-2001, 04:24 AM
  4. Arabic problem view
    By Ayman in forum VB Classic
    Replies: 0
    Last Post: 04-03-2000, 01:08 AM
  5. Problem with CryptoAPI and JCE
    By Jason Bock in forum VB Classic
    Replies: 0
    Last Post: 03-21-2000, 07:48 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center