0

Currently Having my fields like that:

 final JTextField PID = new JTextField("Product ID", 7);
 frame.getContentPane().add(PID);

My method:

public StockItem(Long id, String name, String desc, double price) {
    this.id = id;
    this.name = name;
    this.description = desc;
    this.price = price;
}   

Trying to use this method with values from my JTextFields, but it does not allow to use JTextFields under my Long/String/double places. Is there any way how I could convert my JTextFields into the required things without editing my Method.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
OFFLlNE
  • 747
  • 1
  • 8
  • 17
  • 2
    A `JTextField` will always contain text (String). You can parse, transform, do whatever you want with that. If you want to have a UI control, that allows only numbers, then you can use `JSpinner` for example. – Balázs Édes Oct 27 '14 at 12:16
  • See [this answer](http://stackoverflow.com/a/13424140/1076463) for an example using `JFormattedTextField` – Robin Oct 27 '14 at 12:57

2 Answers2

1

You should use the text field text and parse it.

long l = Long.parseLong(PID.getText());
double d = Double.parseDouble(PID.getText());
cholewa1992
  • 863
  • 1
  • 7
  • 16
0

Yes, you can use PID.getText() to get the text, and then you can convert it to whatever you want, like this:

try{
    long id = Long.parseLong(PID.getText());
    String name = PNAME.getText();
    String description = PDESC.getText();
    double price = Double.parseDouble(PPRICE.getText());
}catch(Exception e){}

I have used the try-catch block because if the user enters something else instead of long in the PID, then it will catch the exception.

dryairship
  • 6,022
  • 4
  • 28
  • 54