当前位置: 动力学知识库 > 问答 > 编程问答 >

windows - How to create Java exception when String is entered instead of integer in JTextField?

问题描述:

I have problems with making exception if you write a String in a JTextField instead od integer. I want to sum input-numbers and write the result on a JButton, every time I clicked it. Every time I click on the button, I get en error:

*

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

at EnaP.actionPerformed(EnaP.java:12)

at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)...

*

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.GridLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class Ena {

public static JTextField a;

public static JTextField b;

public static void main(String[] args) {

JFrame okno = new JFrame();

okno.setSize(400, 200);

a = new JTextField("Number1");

b = new JTextField("Number2");

JButton gumb = new JButton("SUM");

gumb.setPreferredSize(new Dimension(200,200));

EnaP poslusalec = new EnaP();

gumb.addActionListener(poslusalec);

JPanel p = new JPanel();

p.add(a);

p.add(b);

okno.add(gumb, BorderLayout.EAST);

okno.add(p, BorderLayout.WEST);

okno.setTitle("Sum");

okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

okno.setVisible(true);

}

}

and other class - listener:

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

public class EnaP implements ActionListener{

public void actionPerformed(ActionEvent e) {

JButton gumb = (JButton) e.getSource();

try{

String a = Ena.a.getSelectedText().toString();

String b = Ena.b.getSelectedText().toString();

int x = Integer.parseInt(a);

int y = Integer.parseInt(b);

int sum = x+y;

gumb.setText(""+sum);

}

catch (NumberFormatException n) {

System.out.println("Please enter a number.");

}

}

}

I don't know how to fix it...

网友答案:

You have to check for null first, and then throw your own exception for example!

Currently, your code goes:

String a = Ena.a.getSelectedText().toString();

And the fact that you already try to call toString() on the result of getSelectedText() causes that NPE.

You want:

String fieldAsString = Ena.a.getSelectedText();
if (fieldAsString != null) {      
  try {
    int x = Integer.parseInt(fieldAsString);
  ...

instead!

Please note: getSelectedText() already returns a String. There is no point in calling toString() on that String object!

Finally: avoid those nothing telling one character names for your variables. Use names that say what that thing behind the name is about!

网友答案:

You are calling getSelectedText() when you should be calling getText(). The documentation for getSelectedText() says:

Returns the selected text contained in this TextComponent. If the selection is null or the document empty, returns null.

This would only return text if the user had selected all or part of the text in the JTextField. To just get whatever has been typed in the JTextField, use getText().

There are a few other problems with your code. You should not make the text fields public static as doing this is essentially creating global variables. It won't get you in trouble in such a short program, but you will quickly run into trouble as your programs grow.

Instead, make them private, provide getters for them, instantiate an instance of Ena and pass it into the constructor of EnaP, and call the getters to get access to them. That way, only the instance of EnaP that was created to be the action listener for the button in the instance of Ena will be able to access the text fields.

Also, as GhostCat pointed out, your variable names don't convey any information about what they represent or what values they will contain. Again, this doesn't matter much in a very small program, but becomes more and more important the bigger the program gets.

网友答案:

What GhostCat told you is all correct.

Another issue is: Ena.a.getSelectedText() returns the selected (=highlighted) text from the input field. I'm sure that's not what you want.

From the javadoc:

public String getSelectedText()
Returns the selected text contained in this TextComponent.
If the selection is null or the document empty, returns null.

Returns: the text

Throws: IllegalArgumentException - if the selection doesn't have a valid mapping into the document for some reason

Use Ena.a.getText() instead

分享给朋友:
您可能感兴趣的文章:
随机阅读: