简体   繁体   English

JFrame窗体从JTextField添加到JList

[英]JFrame Form add from JTextField to JList

I'm trying to make a contact field where you can type in a first name and a last name in two separate text fields and click the "Add" button I created to send it to the list, but I'm unsure of how to do this exactly, being new to jFrame. 我正在尝试创建一个联系人字段,您可以在其中在两个单独的文本字段中输入名字和姓氏,然后单击我创建的“添加”按钮以将其发送到列表中,但是我不确定如何完全做到这一点,是jFrame的新手。 I was using something in a tutorial that was similar to this using floats (which is shown below), only because I wasn't sure how to use the "String" variation, however this only seems to work when the "setText" command is set on another text field and won't work on a jList. 我在教程中使用的内容与此类似,但使用浮点数(如下所示),只是因为我不确定如何使用“ String”变体,但是,这似乎仅在使用“ setText”命令时才起作用设置在另一个文本字段上,将无法在jList上使用。

float num1, num2, result;
num1 = Float.parseFloat(textFieldFirstName.getText());
num2 = Float.parseFloat(textFieldLastName.getText());
result = num1+num2;
listFieldContact.setText(String.valueOf(result));

Are there any ideas or even good resources out there for jFrame? 是否有关于jFrame的想法或什至好的资源? I've looked in a lot of places but they never quite seem to have exactly the information I need. 我到过很多地方,但似乎从来没有我确切需要的信息。

this only seems to work when the "setText" command is set on another text field and won't work on a jList. 仅当在另一个文本字段上设置了“ setText”命令并且在jList上不起作用时,这才似乎起作用。

A JList doesn't have a setText(...) method. JList没有setText(...)方法。 You need to update the ListModel . 您需要更新ListModel

Read the section from the Swing tutorial on How to Use Lists for a working example that does almost exactly what you want. 阅读Swing教程中有关如何使用列表的部分, 获取一个几乎可以完全满足您需要的工作示例。

The example uses a single text field by you should easily be able to get it to work with two text fields. 该示例使用单个文本字段,您应该很容易就能使它与两个文本字段一起使用。

Try: 尝试:

String fname = textFieldFirstName.getText();
String lname = textFieldLastName.getText();
listFieldContact = fname + " " + lname;

You don't need float conversion, as MadProgrammer pointed out. MadProgrammer指出,您不需要浮点转换。 You do need a space between first and last name. 您的名字和姓氏之间确实需要一个空格。 Maybe you want lname + ", " + fname in other circumstances. 在其他情况下lname + ", " + fname也许您想要lname + ", " + fname

I think to make the values available in the JList it is not necessary to use Float for string operation. 我认为,要使值在JList中可用,就不必对字符串操作使用Float。 We can do it like this : 我们可以这样做:

Vector<String> nameVector = new Vector<>();
JList<String> nameList = new JList<>();

public void addText() {
    nameVector.add(firstNameTF.getText()+lastNameTF.getText());
    nameList.setListData(nameVector);
}

I think this piece of code will help you to solve your query. 我认为这段代码将帮助您解决查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM