我想知道,如何通过 Java GUI 中的新面板添加新项目。
我有类(class)程序
public class Program extends javax.swing.JFrame {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public int pos;
public Program() {
contacts.add(new Contact("John Tavares", "736426436", "Prague"));
contacts.add(new Contact("John Doe", "725847896", "NY"));
contacts.add(new Contact("Damien Smith", "725589963", "London"));
pos = 0;
initComponents();
}
然后是一些显示ArrayList内容的标签,它工作正常。在 Contact
类中包含姓名、电话和城市。
我有 JButton New Contact,它打开了新的面板 NewContact,其中包含姓名、电话和城市的文本字段,当然还有 OK JButton。这也很好用。
有人可以帮我吗,我如何从 NewContact 中的文本字段中获取文本并将它们添加到 ArrayList 中?
感谢您的建议
最佳答案
如果我理解正确的话,你想用一个按钮添加联系人。 首先你必须创建一个新按钮:
private JButton mybutton = new JButton("Add");
然后你必须重写actionListener
private void addActionListener() {
mybutton.addActionListener(this);
}
然后你必须知道你按下的是哪种按钮:
@Override
public void actionPerformed (ActionEvent e) {
Object source = e.getSource();
if(source == mybutton)
contacts.add(something);
}
关于java - 使用新面板向 ArrayList 添加新项目 - swing Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16306854/