简体   繁体   English

用Java动态创建GUI组件

[英]Creating GUI components dynamically in java

So, we can create for example a button dynamically: 因此,我们可以动态创建一个按钮:

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

But the question is, how do we make calls to those elements later? 但是问题是,我们以后如何调用这些元素? For example, how do I add an event listener to this button created above, like, 100 lines of code later? 例如,如何将事件侦听器添加到上面创建的此按钮上,例如稍后添加100行代码?

I've always created my buttons before adding to the panel like so 我总是在创建按钮之前先创建按钮,如下所示

   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;
    }

Allows you do something like this later on. 稍后允许您执行类似的操作。

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

Create a variable for your JButton: 为您的JButton创建一个变量:

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

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

In order to bind event listeners or other functionality into the button, you'd need to store a reference to it in a variable. 为了将事件侦听器或其他功能绑定到按钮,您需要将对它的引用存储在变量中。 So, instead of 所以,代替

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

You could initialize the button with 您可以使用初始化按钮

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

and then later in your code 然后在您的代码中

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

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

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