如何在另一个按钮内部创建的按钮上添加功能?

时间:2018-07-07 16:32:32

标签: java swing user-interface events

我的问题是,我不知道如何添加其操作,您已经看到,某些按钮已经被编程,并且每个按钮都具有人员(安装程序)的名称,并且其功能是单击时,我会自动复制您的id,然后随着时间的推移会出现新的安装程序,我希望能够使我的程序适合普通人群,然后我认为除了安装程序外还添加了一个按钮,以便他们可以添加越来越多的内容,我需要该人创建的每个按钮都具有与其他按钮相似的功能。

这是我的局限性,我不知道您的函数将在哪里或如何运行:

private void addInstallerActionPerformed(ActionEvent evt){
    JButton newInstaller = new JButton("New Button");
    panel.add(newInstaller);
    validate();
}

这是我的整个代码:

class Billing {

    public static void main(String[] args) {

        mainWindow w = new mainWindow();
        w.setVisible(true);
        w.setSize(1280,720);
        w.setLocationRelativeTo(null);

    }
}

class mainWindow extends JFrame implements ActionListener{

    JPanel panel;
    JButton andresTorres, alexanderHernandez, eduardoRuiz, jorgeFley, addInstaller;
    public mainWindow(){

        panel = new JPanel();
        //Instaladores
        andresTorres = new JButton("Andres Torres");
        alexanderHernandez = new JButton("Alexander Hernandez");
        eduardoRuiz = new JButton("Eduardo Ruiz");
        jorgeFley = new JButton("Jorge Fley");
        addInstaller = new JButton("add Installer");
        //End

        add(panel);

        panel.add(andresTorres);
        panel.add(alexanderHernandez);
        panel.add(eduardoRuiz);
        panel.add(jorgeFley);
        panel.add(addInstaller);

        setTitle("Billing assistant");
        setDefaultCloseOperation(this.EXIT_ON_CLOSE);

        andresTorres.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                andresTorresActionPerformed(evt);
            }
        });


        alexanderHernandez.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                alexanderHernandezActionPerformed(evt);
            }
        });

        eduardoRuiz.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                eduardoRuizActionPerformed(evt);
            }
        });

        jorgeFley.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                jorgeFleyActionPerformed(evt);
            }
        });

        addInstaller.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                addInstallerActionPerformed(evt);
            }
        });
    }

    private void addInstallerActionPerformed(ActionEvent evt){
    JButton newInstaller = new JButton("New Button");
    panel.add(newInstaller);
    validate();
}

    private void andresTorresActionPerformed(ActionEvent evt){
            String myString = "here goes your identification";
            StringSelection stringSelection = new StringSelection(myString);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
        }

    private void alexanderHernandezActionPerformed(ActionEvent evt){
            String myString = "here goes your identification";
            StringSelection stringSelection = new StringSelection(myString);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
        }

    private void eduardoRuizActionPerformed(ActionEvent evt){
            String myString = "here goes your identification";
            StringSelection stringSelection = new StringSelection(myString);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
        }

    private void jorgeFleyActionPerformed(ActionEvent evt){
            String myString = "here goes your identification";
            StringSelection stringSelection = new StringSelection(myString);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);
        }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

请帮助我。

1 个答案:

答案 0 :(得分:1)

您有太多的代码冗余,没有足够的OOP -没有足够多的独立对象,每个对象都有其自己的状态和行为。我建议:

  • 首先,要创建一个Person类,该类将一个人的姓名保存为String以及要复制到与该姓名相关联的剪贴板的ID信息,以及其他任何字段和方法。将字段设置为私有实例字段,并为类提供适当的构造函数和getter(可能还有setter)。
  • 创建一个ActionListener类(或者更好的是AbstractAction,类似于在类固醇上的ActionListener),在其私有字段中保存一个Person对象。通过构造函数参数将此Person传入。在侦听器中,包含将此人的ID放入剪贴板的代码。

例如,最简单的例子:

public class Person {
    String name;
    String identification;

    public Person(String name, String identification) {
        this.name = name;
        this.identification = identification;
    }

    public String getName() {
        return name;
    }

    public String getIdentification() {
        return identification;
    }

}

class PersonAction extends AbstractAction {
    private Person person;

    public PersonAction(Person person) {
        super(person.getName());
        this.person = person;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        StringSelection stringSelection = new StringSelection(person.getIdentification());

        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);
    }
}

然后在安装程序按钮的ActionListener中,可以使用此Action创建按钮并将其添加到需要的位置。例如:

        @Override
        public void actionPerformed(ActionEvent e) {

            // assuming two JTextFields in the app, nameField and idField
            String name = nameField.getText();
            String identification = idField.getText();

            // create new Person with the name and id information
            Person person = new Person(name, identification);

            // create a new PersonAction with the Person above 
            // and pass into a JButton
            JButton personButton = new JButton(new PersonAction(person));

            // assuming a JPanel called personPanel that holds these JButtons
            personPanel.add(personButton);  // add the button 
            personPanel.revalidate();  // tell the panel to relayout components
            personPanel.repaint();  // and repaint
        }

完整的简单示例:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;    
import javax.swing.*;

@SuppressWarnings("serial")
public class MainWindowApp2 extends JPanel {
    private JPanel personPanel = new JPanel(new GridLayout(0, 1, 4, 4));
    private JTextField nameField = new JTextField(10);
    private JTextField idField = new JTextField(10);

    public MainWindowApp2() {
        personPanel.add(new JButton(new PersonAction(new Person("Andres Torres", "AT 001"))));
        personPanel.add(new JButton(new PersonAction(new Person("Alexander Hernandez", "AH 002"))));
        personPanel.add(new JButton(new PersonAction(new Person("Eduardo Ruiz", "ER 003"))));
        personPanel.add(new JButton(new PersonAction(new Person("Jorge Fley", "JF 004"))));
        personPanel.add(new JButton(new PersonAction(new Person("Miguél Gonzales", "MG 005"))));

        JButton addInstallerButton = new JButton(new AbstractAction("Add Installer") {

            @Override
            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String identification = idField.getText();
                Person person = new Person(name, identification);

                JButton personButton = new JButton(new PersonAction(person));
                personPanel.add(personButton);
                personPanel.revalidate();
                personPanel.repaint();
            }
        });

        JPanel topPanel = new JPanel();
        topPanel.add(new JLabel("Name:"));
        topPanel.add(nameField);
        topPanel.add(new JLabel("ID:"));
        topPanel.add(idField);
        topPanel.add(addInstallerButton);

        JPanel personWrapperPanel = new JPanel(new BorderLayout());
        personWrapperPanel.add(personPanel, BorderLayout.PAGE_START);

        JScrollPane scrollPane = new JScrollPane(personWrapperPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setPreferredSize(new Dimension(600, 600));
        setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        setLayout(new BorderLayout(4, 4));
        add(scrollPane);
        add(topPanel, BorderLayout.PAGE_START);
    }

    private static void createAndShowGui() {
        MainWindowApp2 mainPanel = new MainWindowApp2();

        JFrame frame = new JFrame("MainWindowApp2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}