Results 1 to 6 of 6
  1. #1
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default JTextField question

    Hi. I'm making a program that, as of now, just adds, subtracts, multiplies, or divides two numbers. This is the code I have so far --

    Java Code:
    public class Functions {
    	
    	
    	public double add(double a, double b) {
    		return a + b;		
    	}
    	
    	public double subtract(double a, double b) {
    		return a - b;
    	}
    	
    	public double multiply(double a, double b) {
    		return a*b;
    	}
    	
    	public double divide(double a, double b) {
    		return a/b;
    	}
    	
    	public double squareRoot(double a) {
    		return Math.sqrt(a);
    	}
    	
    	public double takePower(double a, double exp) {
    		for(int i=0;i<exp;i++) {
    			a = a * a;
    		}
    		return a;
    	}
    	
    
    }
    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    
    public class Player{
    
    	public Functions functions = new Functions();
    	public JFrame frame;
    	public JPanel panel;
    	public JButton addButton;
    	public JButton subtractButton;
    	public JButton multiplyButton;
    	public JButton divideButton;
    	public JLabel label;
    	
    	public static void main(String[] args) {
    		Player player = new Player();
    		player.go();
    		
    	}
    	
    	public void go() {
    		frame = new JFrame();			//initiate the Frame, Panel, and Label
    		panel = new JPanel();
    		label = new JLabel(" ");
    		addButton = new JButton("Add");		//initiate the add button and give it a listener
    		addButton.addActionListener(new AddListener());
    		subtractButton = new JButton("Subtract");	//initiate the subtract button and give it a listener
    		subtractButton.addActionListener(new SubtractListener());
    		multiplyButton = new JButton("Multiply");	//initiate the multiply button and give it a listener
    		multiplyButton.addActionListener(new MultiplyListener());
    		divideButton = new JButton("Divide");	//initiate the divide button and give it a listener
    		divideButton.addActionListener(new DivideListener());
    		panel.add(addButton);		//add everything to the panel, then to the frame
    		panel.add(subtractButton);
    		panel.add(multiplyButton);
    		panel.add(divideButton);
    		panel.add(label);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	//set things for the frame
    		frame.setSize(400, 400);
    		frame.add(panel);
    		frame.setVisible(true);
    		
    	}
    	
    	
    	class AddListener implements ActionListener {
    		public void actionPerformed(ActionEvent event) {
    			JTextField first = new JTextField(1);
    			JTextField second = new JTextField(1);
    			String string = "" + functions.add(Double.parseDouble(first.getText()), Double.parseDouble(second.getText()));
    			label.setText(string);
    		}
    	}
    	class SubtractListener implements ActionListener {
    		public void actionPerformed(ActionEvent event) {
    
    		}
    	}
    	
    	class MultiplyListener implements ActionListener {
    		public void actionPerformed(ActionEvent event) {
    
    		}
    	}
    	
    	class DivideListener implements ActionListener {
    		public void actionPerformed(ActionEvent event) {
    
    		}
    	}
    
    }
    I want two text fields to open for you to put in two numbers whenever you click a button. Whenever I click the add button this message comes up --

    Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Unkn own Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at Player$AddListener.actionPerformed(Player.java:50)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

    I'm like 99.9% sure it's a problem with the text fields, but I don't know how to fix it. Is there a way I can get two text fields to pop up, wait to enter two numbers, then add? Or is there any other way I can go about doing this? Any help is appreciated.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Regarding this code:
    Java Code:
        public void actionPerformed(ActionEvent event) {
          JTextField first = new JTextField(1);
          JTextField second = new JTextField(1);
          String string = ""
              + functions.add(Double.parseDouble(first.getText()), Double
                  .parseDouble(second.getText()));
          label.setText(string);
        }
    All this does is create empty JTextFields that are never placed in a container and never displayed, and then tries to extract and parse text from these non-displayed textfields which of course will throw a bunch of errors.

    Why not just add the JTextFields to your panel from the beginning, and then in the actionPerformed, check what they contain, but do this with error checking so you don't get errors.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, if the JTextFields absolutely must "pop up", then place them in a JPanel and then the JPanel into JDialog, and display it, but it seems like a bit of extra unnecessary work both for the coder and the user.

    Also, other issues are present including the exp being a double and not an int, and checking for divide by zero before doing division, but one thing at a time here.

  4. #4
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    logic error
    Java Code:
    	public double takePower(double a, double exp) {
    		[B]for(int i=0;i<exp;i++) {
    			a = a * a;[/B]
    		}
    		return a;
    	}
    so 2^4 = ?
    Java Code:
    while(i<exp)
       a = 2 * 2 = 4, i=0
       a = 4 * 4 = 16, i=1
       a = 16 * 16 = .....
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by angryboy View Post
    logic error
    Good point!

    To the original poster, sorry I got a bit carried away with this one...
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class SimpleAddApp extends JPanel {
      private JTextField field1 = new JTextField(10);
      private JTextField field2 = new JTextField(10);
      private JTextField resultField = new JTextField(20);
    
      public SimpleAddApp() {
        ButtonListener btnListener = new ButtonListener();
        JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 10, 0));
        for (ButtonCommands command : ButtonCommands.values()) {
          JButton button = new JButton(command.getText());
          button.addActionListener(btnListener);
          buttonPanel.add(button);
        }
    
        JPanel fieldPanel = new JPanel(new GridLayout(1, 0, 10, 0));
        fieldPanel.add(field1);
        fieldPanel.add(field2);
        
        resultField.setEditable(false);
        JPanel resultPanel = new JPanel(new GridLayout(1, 0, 10, 0));
        resultPanel.add(resultField);
    
        setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        add(buttonPanel);
        add(Box.createVerticalStrut(20));
        add(fieldPanel);
        add(Box.createVerticalStrut(20));
        add(resultPanel);
      }
    
      public void clearFields() {
        field1.setText("");
        field2.setText("");
      }
    
      private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent actionEvent) {
          resultField.setText("");
          try {
            double d1 = Double.parseDouble(field1.getText());
            double d2 = Double.parseDouble(field2.getText());
    
            String actionCommand = actionEvent.getActionCommand();
            BinaryOp binaryOp = null;
            for (ButtonCommands buttonCommand : ButtonCommands.values()) {
              if (buttonCommand.getText().equals(actionCommand)) {
                binaryOp = buttonCommand.getBinaryOp();
                break;
              }
            }
            String resultString = String.format("%s(%.2f, %.2f) = %.2f",
                actionCommand, d1, d2, 
                binaryOp.execute(d1, d2));
            resultField.setText(resultString);
          } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(SimpleAddApp.this,
                "Only numbers should be entered", "Non-Numeric Input",
                JOptionPane.ERROR_MESSAGE);
            SimpleAddApp.this.clearFields();
          }
        }
      }
    
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("SimpleAddApp Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new SimpleAddApp());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
    
      }
    }
    
    interface BinaryOp {
      double execute(double d1, double d2);
    }
    
    enum ButtonCommands {
      ADD("Add", new BinaryOp() {
        public double execute(double d1, double d2) {
          return d1 + d2;
        }
      }), 
      SUBTRACT("Subtract", new BinaryOp() {
        public double execute(double d1, double d2) {
          return d1 - d2;
        }
      }), 
      MULTIPLY("Multiply", new BinaryOp() {
        public double execute(double d1, double d2) {
          return d1 * d2;
        }
      }), 
      DIVIDE("Divide", new BinaryOp() {
        public double execute(double d1, double d2) {
          return d1 / d2;
        }
      });
      private String text;
      private BinaryOp binaryOp;
      private ButtonCommands(String text, BinaryOp binaryOp) {
        this.text = text;
        this.binaryOp = binaryOp;
      }
      public String getText() {
        return text;
      }
      public BinaryOp getBinaryOp() {
        return binaryOp;
      }
    }
    But seriously, at least you can see how I add JTextFields to the JPanel and then use them in the ActionListener

  6. #6
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Awesome! Thanks for the useful feedback. I knew the text fields were messed up, but I just didn't know how to go about fixing it. About exp being a double instead of int -- I know 9 times out of 10 exponents will be an integer, but I just figured I would go ahead and set it as a double so that I can test using fractions.

    Haha don't be sorry, I am happy to get any feedback I can. I'd rather you tell me too much than nothing at all. Anyways, thanks. You might see this program posted in later days with new questions heh.

Similar Threads

  1. Problem's with JTextField
    By DC% in forum AWT / Swing
    Replies: 4
    Last Post: 03-10-2009, 05:33 PM
  2. AutoComplete for jtextfield
    By pinks_70986 in forum New To Java
    Replies: 2
    Last Post: 02-12-2009, 06:46 AM
  3. Replies: 1
    Last Post: 01-30-2009, 06:44 PM
  4. JtextField
    By kashifu in forum Advanced Java
    Replies: 2
    Last Post: 06-27-2008, 04:25 PM
  5. help with JTextfield
    By gary in forum New To Java
    Replies: 4
    Last Post: 07-11-2007, 01:58 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
  •