1 Replies - 286 Views - Last Post: 02 February 2013 - 04:22 PM Rate Topic: -----

#1 treyriggins  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 12-January 13

How to Use ActionListener for User pressing ENTER in JTextField

Posted 02 February 2013 - 03:26 PM

This is my output constructor where all my calculations are done. I am working on trying to let user Press ENTER in JTextField labeled inputbox and I am stuck. Can someone please give me some guidance or direction here?


public void outputConvertedTemp()
	{
		
		//reads buttons selected to determine output
		double temp;
		double newtemp = 0;
		temp = Double.parseDouble(inputbox.getText());
		
		if (CelsiusIn.isSelected() & KelvinOut.isSelected())
				newtemp = (temp + 273.15);//c to k
		else if (FahrenheitIn.isSelected() & KelvinOut.isSelected())
				newtemp = ((temp + 459.67) * 0.556);//f to k
		else if (KelvinIn.isSelected() & FahrenheitOut.isSelected())
			newtemp = (((temp * 1.8) - 459.67));//k to f
		else if (CelsiusIn.isSelected() & FahrenheitOut.isSelected())
			newtemp = (((1.8) * temp) + 32);//c to f
		else if (FahrenheitIn.isSelected() & CelsiusOut.isSelected())
			newtemp = ((.556) * (temp - 32));//f to c
		else if (KelvinIn.isSelected() & CelsiusOut.isSelected())
			newtemp = (temp - 273.15);//k to c
		//the following are to ensure that the output stays what it should be
		else if (CelsiusIn.isSelected() & CelsiusOut.isSelected())
			newtemp = temp;
		else if (FahrenheitIn.isSelected() & FahrenheitOut.isSelected())
			newtemp = temp;
		else if (KelvinIn.isSelected() & KelvinOut.isSelected())
			newtemp = temp;
		String degree = "" + (char)186;
		outputbox.setText("" + two.format(newtemp) + degree);
	}



Is This A Good Question/Topic? 0
  • +

Replies To: How to Use ActionListener for User pressing ENTER in JTextField

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: How to Use ActionListener for User pressing ENTER in JTextField

Posted 02 February 2013 - 04:22 PM

Take a look at the tutorial "How to Write a Key Listener" and there you will learn about a method called "keyPressed" which is passed a KeyEvent argument when the user presses a key. That KeyEvent can be compared to the constant KeyEvent.VK_ENTER to check if the enter key was pressed.

You can attach the listener to the textfield by using the addKeyListener() method.

:)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1