Reputation:
I am doing work with text field i make a program in which user type i in text field it converts into int i but the problem is when user type i it doesn't convert into int i.The Condition does not work correctly why its happening.
public class A extends JFrame{
private JTextField entervar;
private JButton button;
public A(){
getContentPane().setLayout(null);
entervar = new JTextField();
entervar.setToolTipText("variable must be 'i'");
entervar.setBounds(37,26,89,28);
getContentPane().add(entervar);
button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String p = entervar.getText();
try {
int i;
if ( p.equals("i") ) {
i = Integer.parseInt(p);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog (null, "Enter Variable Must be i");
}
}
});
button.setBounds(108,121,89,28);
getContentPane().add(button);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main:
public class Main {
public static void main(String[] args) {
A obj = new A();
}
}
Upvotes: 2
Views: 60
Reputation: 57381
p.equals("i")
means user enters "i" in the text field. SO it can't be converted to number "i" is not number.
Read about JFormattedTextField. You can set NumberModel for int and get integer directly.
Upvotes: 1