Java have a int value using setText

橙三吉。 提交于 2020-01-30 11:47:48

问题


I'm trying to set an int value using jTextField and the setText method. But of course setText wants a String. How do I get round this? I'll give you a snippet of the code:

    private void setAllTextFields(FilmSystem e){
    getFilmNameTF().setText(e.getFilmName());
    lectureTF.setText(e.getLecture());
    ageTF.setText(e.getAge());
    priceTF.setText(e.getTicketCost());
    seatsTF.setText(e.getNoOfSeats());

seatsTF is a jTextField and getNoOfSeats is a method in another class that returns a int value.

Thanks again for answering this question. Now how would I go about getting the value of the int to do something to do?

        public void buyTicket() {
    String newFilmName = filmNameTF.getText();
    String newLecture = lectureTF.getText();
    String newAge = ageTF.getText();
    String newPrice = priceTF.getText(); 
    int newSeats = seatsTF.

As you can see the code, the String values I can get easy with getText. I can then print them out or whatever with them. How can I do this with the seats int? Thanks again.


回答1:


String#valueOf convert your int to String.

String.valueOf(e.getAge()); will return the string representation of the int argument.

seatsTF.setText(String.valueOf(e.Age()));
...



回答2:


USe

seatsTF.setText(""+e.getNoOfSeats());

OR

seatsTF.setText(String.valueOf(e.getNoOfSeats()));



回答3:


Normal ways would be

seatsTF.setText(Integer.toString(e.getNoOfSeats()));

or

seatsTF.setText(String.valueOf(e.getNoOfSeats()));

but, this can be achieved with a concatenation like this:

seatsTF.setText("" + e.getNoOfSeats());



回答4:


Assuming age field is of type int, you could try something like:

        ageTF.setText( Integer.toString(e.getAge()) );



回答5:


Setting an int converting it to a String not a big deal. Displaying a value is a problem. To take care of how the value is displayed properly in the textfield you may use a DecimalFormat to format the numeric value. But may be the number is locale specific then you need NumberFormat instance

NumberFormat nf = NumberFormat.getInstance(locale);
nf.setMaximumIntegerDigits(12);
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
String s = nf.format(e.getNoOfSeats());
seatsTF.setText(s);

You may also need to read the tutorial on how to use the DecimalFormat.




回答6:


To convert Integer Value to String you should

MedicineTM medicine=tblmedicine.getSelectionModel().getSelectedItem();

    txtmedicine.setText(medicine.getMID());
    txtDescription.setText(medicine.getDescription());
    txtQty.setText(String.valueOf(medicine.getQty()));  // this is what i did
    cmbApproval.setValue(medicine.getApproval());



回答7:


I think you should write the code as

seatsTF.setText(e.getNoOfSeats().toString());



来源:https://stackoverflow.com/questions/15530370/java-have-a-int-value-using-settext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!