我正在尝试从Jframe表单的用户输入创建多个对象。我在这里看到很多关于如何使用控制台执行此操作的帖子,所有答案最终都放在循环中;但是没有人问如何从Jframe表格中做到这一点。
private void CreateAccount() {
String selected = UserSelectList.getSelectedValue();
String setName = nameTboxSet.getText();
String setType = UserTypeBoxSet.toString();
if ("user1" == selected) {user1.setName(setName); user1.setUserType(setType);}
else if ("user2" == selected) {user2.setName(setName); user2.setUserType(setType);}
else if ("user3" == selected) {user3.setName(setName); user3.setUserType(setType);}
else if ("user4" == selected) {user4.setName(setName); user4.setUserType(setType);}
else if ("user5" == selected) {user5.setName(setName); user5.setUserType(setType);}
else if ("user6" == selected) {user6.setName(setName); user6.setUserType(setType);}
else if ("user7" == selected) {user7.setName(setName); user7.setUserType(setType);}
else if ("user8" == selected) {user8.setName(setName); user8.setUserType(setType);}
else if ("user9" == selected) {user9.setName(setName); user9.setUserType(setType);}
else if ("user10" == selected) {user10.setName(setName); user10.setUserType(setType);}
}
以上是我目前提出的内容,但老实说,我不认为列表是必要的,我已经尝试了许多方法来尝试找出如何使这项工作。
答案 0 :(得分:1)
在您的代码中,您错误地确定了哪个项目已被选中。假设您使用了java.awt.List组件,这就是您尝试实现的目标。
if (listName.getSelectedItem.equals(“user1”)){ ... }
有关此内容的更多信息,请访问List组件的Oracle文档:https://docs.oracle.com/javase/7/docs/api/java/awt/List.html
我编写了一个快速示例,向您展示它的实际效果:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TestFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
List list = new List();
list.add("user1", 0);
list.add("user2", 1);
list.add("user3", 2);
list.add("user4", 3);
list.add("user5", 4);
list.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(list.getSelectedItem().equals("user1")){
System.out.println("User 1 has been selected!");
}else if(list.getSelectedItem().equals("user2")){
System.out.println("User 2 has been selected!");
}
}
});
contentPane.add(list);
setContentPane(contentPane);
}
}