在java中动态创建GUI组件

时间:2017-09-13 20:54:43

标签: java swing

因此,我们可以动态创建一个按钮:

panel.add(new JButton("Button"));
validate();

但问题是,我们如何在以后调用这些元素?例如,如何向上面创建的此按钮添加事件侦听器,例如,以后的100行代码?

3 个答案:

答案 0 :(得分:1)

在添加到面板之前,我总是创建我的按钮

   private JPanel buttonPanel() { //button panel method containting 
        JPanel panel = new JPanel();
        JButton addButton = new JButton("Add");
        addButton.setToolTipText("Add Customer Data");
        JButton editButton = new JButton("Edit");
        editButton.setToolTipText("Edit selected Customer");
        JButton deleteButton = new JButton ("Delete");
        deleteButton.setToolTipText("Delete selected Customer");

        addButton.addActionListener((ActionEvent) -> {
            doAddButton();
        });
        editButton.addActionListener((ActionEvent) -> {
            doEditButton();
        });
        deleteButton.addActionListener((ActionEvent) -> {
            doDeleteButton();
        });

        panel.add(addButton);
        panel.add(editButton);
        panel.add(deleteButton);

        return panel;
    }

允许您稍后执行此类操作。

    private void doAddButton() { //provides action for add button
    CustomerForm customerForm = new CustomerForm(this, "Add Customer", true);
    customerForm.setLocationRelativeTo(this);
    customerForm.setVisible(true);
}

答案 1 :(得分:1)

为JButton创建一个变量:

JButton jButton = new JButton("Button");
panel.add(jButton);
validate();
/*
 *
 *
100 lines of code 
 *
 */

// add an event listener
jButton.addActionListener((ActionEvent) -> {
            // do something
        });

答案 2 :(得分:0)

为了将事件侦听器或其他功能绑定到按钮中,您需要在变量中存储对它的引用。所以,而不是

panel.add(new JButton("Button"));

您可以使用

初始化按钮
JButton myButton = new JButton("Button");
panel.add(myButton);

然后在你的代码中

myButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
         // do something
     } 
});