import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.border.Border; public class TempConvertor extends JFrame implements ActionListener { JButton Convert; JButton Reset; JTextField Cel; JTextField Fah; JLabel CelLbl; JLabel farenheight; TempConvertor() { JFrame j = new JFrame("Temp Convertor"); j.setSize(200,175); j.setResizable(false); j.setLayout(new FlowLayout()); j.setDefaultCloseOperation(EXIT_ON_CLOSE); //create buttons Convert = new JButton("Convert"); Reset = new JButton("Reset"); Convert.addActionListener(this); Reset.addActionListener(this); //create labels CelLbl = new JLabel("Celsius"); farenheight = new JLabel("Farenheight"); CelLbl.setVerticalAlignment(SwingConstants.BOTTOM); farenheight.setVerticalAlignment(SwingConstants.BOTTOM); Border border = BorderFactory.createEtchedBorder(); CelLbl.setBorder(border); farenheight.setBorder(border); JPanel cp = ((JPanel) j.getContentPane()); cp.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); //create text fields Cel = new JTextField(5); Fah = new JTextField(5); Cel.setActionCommand("Cel"); Fah.setActionCommand("Fah"); //add TextFields j.add(CelLbl); j.add(Cel); j.add(farenheight);//label j.add(Fah); //add Buttons j.add(Convert); j.add(Reset); j.setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("Convert")) { if(Cel != null) { //convert to Cel int jml = Integer.parseInt(Cel.getText()); int result = jml * 9/5 + 32; Fah.setText(Integer.toString(result)); } else if(Fah != null) { //convert to Fah int jml = Integer.parseInt(Fah.getText()); int result = (jml - 32) * 5/9; Cel.setText(Integer.toString(result)); } } else { Cel.setText(""); Fah.setText(""); } } public static void main(String[] args) { new TempConvertor(); } }
I am learning java swing and I am having an issue on line 78. I want to convert Celsius to Fahrenheit which works. However when I try to convert F to C I get the following errors:
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
I thought my if statement would handle this for me but only my Cel JTextField seems to be working. Any Advice?