如何使用"ADD"按钮反复添加JPanel?如何在ActionListener()中调用JPanel? [英] How to add a JPanel repeatedly using an 'ADD' button? How to call a JPanel in the ActionListener()?

查看:132
本文介绍了如何使用"ADD"按钮反复添加JPanel?如何在ActionListener()中调用JPanel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用添加"按钮重复就业历史记录" JPanel(内容为灰色),然后使用删除"按钮将其删除.

I want to repeat the Employment History JPanel(with the contents in grey), by using the ADD button and remove it by using Remove button.This is the GUI I would also like to know how to store the values of the textfields temporarily. Will an array be helpful?

这是代码

    JLabel lblEmploymentHistory = new JLabel("Employment History:");
    lblEmploymentHistory.setBounds(46, 145, 128, 14);
    frame.getContentPane().add(lblEmploymentHistory);

    JPanel panelemp = new JPanel();
    panelemp.setBounds(46, 170, 435, 63);
    panelemp.setBackground(Color.GRAY);
    frame.getContentPane().add(panelemp);

    JLabel lblRoleHeld = new JLabel("Role Held:");
    panelemp.add(lblRoleHeld);

    txtRole = new JTextField();
    txtRole.setText("role");
    panelemp.add(txtRole);
    txtRole.setColumns(10);

    JLabel lblDuration = new JLabel("Duration:");
    panelemp.add(lblDuration);

    txtDuration = new JTextField();
    txtDuration.setText("duration");
    panelemp.add(txtDuration);
    txtDuration.setColumns(10);

    JLabel lblEmployer = new JLabel("Employer:");
    panelemp.add(lblEmployer);

    txtEmployer = new JTextField();
    txtEmployer.setText("employer");
    panelemp.add(txtEmployer);
    txtEmployer.setColumns(10);

    JButton Addnewemphis = new JButton("Add");
    Addnewemphis.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

        }
    });
    panelemp.add(Addnewemphis);

    JButton btnRemove = new JButton("Remove");
    btnRemove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });
    panelemp.add(btnRemove);

推荐答案

先退后一步.您需要学习和理解一个关键概念-责任分离.

Take a step back first. There is a critical concept you need to learn and understand - Separation of Responsibilities.

您需要将功能分开并将其隔离到各个类中,这将使快速,简单地开发重复功能变得更加容易.

You need to separate and isolate your functionality into individual classes, this will make it easier to develop repeated functionality quickly and simply.

您还应该集中精力将数据"的管理与用户界面"分开,以便用户界面代表数据,并用于(在适用时)更新数据.

You should also be focused on separating the management of your "data" from the "user interface", so that the user interface is a representation of your data and is used to (where applicable) update it.

根据您当前的设计,无法选择"员工历史记录面板,因此执行通用"删除操作是没有意义的-您将删除哪个?相反,该操作实际上属于员工历史记录面板本身,但是添加和删除这些组件的责任完全由一个单独的控制器负责.

Based on your current design, there's no way to "select" a employee history panel, so having a "generic" remove action is pointless - which one would you remove? Instead, the action actually belongs with the employee history panel itself, but the responsibility to add and remove these components resides with a seperate controller altogether.

让我们从一个基本概念开始,您首先需要一些数据...

Let's start with a basic concept, you need some data first...

public class EmployeeHistory {

    private String role;
    private String duration;
    private String employer;

    public EmployeeHistory() {
    }

    public EmployeeHistory(String role, String duration, String employer) {
        this.role = role;
        this.duration = duration;
        this.employer = employer;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public String getEmployer() {
        return employer;
    }

    public void setEmployer(String employer) {
        this.employer = employer;
    }

}

我个人更希望使用interface,对于只读"访问和读写"访问,可能会使用interface,但是为了简洁起见,我们会坚持使用它.

Personally, I'd prefer a interface, possible one for "read-only" and for "read-write" access, but we'll stick with this for brevity.

接下来,我们需要某种方式来显示它...

Next, we need some way to display it...

public class HistoryPane extends JPanel {

    private final JTextField txtRole;
    private final JTextField txtDuration;
    private final JTextField txtEmployer;

    private final JButton removeButton;

    private EmployeeHistory history;

    public HistoryPane(EmployeeHistory history) {
        // This is what you should use when you want to populate
        // the view or properties of the UI are changed
        this.history = history;
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;

        JLabel lblRoleHeld = new JLabel("Role Held:");
        add(lblRoleHeld, gbc);

        gbc.gridx++;
        txtRole = new JTextField();
        txtRole.setText("role");
        add(txtRole, gbc);
        txtRole.setColumns(10);

        gbc.gridx = 0;
        gbc.gridy++;
        JLabel lblDuration = new JLabel("Duration:");
        add(lblDuration, gbc);

        gbc.gridx++;
        txtDuration = new JTextField();
        txtDuration.setText("duration");
        add(txtDuration, gbc);
        txtDuration.setColumns(10);

        gbc.gridx = 0;
        gbc.gridy++;
        JLabel lblEmployer = new JLabel("Employer:");
        add(lblEmployer, gbc);

        gbc.gridx++;
        txtEmployer = new JTextField();
        txtEmployer.setText("employer");
        add(txtEmployer, gbc);
        txtEmployer.setColumns(10);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        removeButton = new JButton("Remove");
        add(removeButton, gbc);
    }

    public EmployeeHistory getHistory() {
        return history;
    }

    public void addActionListener(ActionListener listener) {
        removeButton.addActionListener(listener);
    }

    public void removeActionListener(ActionListener listener) {
        removeButton.removeActionListener(listener);
    }

}

nb:我没有费心用数据填充视图,我敢肯定您可以解决问题

这里要注意的是removeButton实际上并没有做任何事情,责任被委派给其他人

The thing to notice here is that the removeButton doesn't actually do anything, the responsibility is delegated to some other party

好的,我们可以删除,但是我们如何添加呢?好吧,您需要另一个组件……

Okay, we can remove, but how do we add? Well, you need another component for that...

public class ActionPane extends JPanel {

    private JButton btn;

    public ActionPane() {
        setLayout(new GridBagLayout());
        btn = new JButton("Add");
        add(btn);
    }

    public void addActionListener(ActionListener listener) {
        btn.addActionListener(listener);
    }

    public void removeActionListener(ActionListener listener) {
        btn.removeActionListener(listener);
    }

}

同样,这实际上什么也没做,只是将责任委托给其他人.

Again, this doesn't actually do anything, it simply delegates the responsibility to some one else.

nb:这是一个基本示例,同样,您可以传入某种充当代理的控制器,但结果基本相同

好的,但是这一切如何工作?好吧,您只需要一起研究所有功能...

Okay, fine, but how does this all work? Well, you just need to plumb all the functionality together...

所以这是添加和删除功能的可能实现方式

So this is a possible implementation of both the add and remove functionality

ActionPane actionPane = new ActionPane();
actionPane.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Layout constraints
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // The actually history data
        EmployeeHistory history = new EmployeeHistory();
        // This is a model to manage the individual histories, making
        // it easier to manage
        histories.add(history);
        // The history view...
        HistoryPane pane = new HistoryPane(history);
        // The remove action...
        pane.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Remove the action to improve the chances of been
                // garbage collected
                pane.removeActionListener(this);
                // Remove the history from our model
                histories.remove(pane.getHistory());
                // Remove the view
                contentPane.remove(pane);
                contentPane.revalidate();
                contentPane.repaint();
            }
        });
        // Add the view (this is a little trick ;))
        contentPane.add(pane, gbc, contentPane.getComponentCount() - 1);
        contentPane.revalidate();
        contentPane.repaint();
    }
});

可运行的示例

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPanel contentPane;
        private List<EmployeeHistory> histories;

        public TestPane() {
            histories = new ArrayList<>(25);
            setLayout(new BorderLayout());

            contentPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weighty = 1;
            contentPane.add(new JPanel(), gbc);

            JScrollPane scrollPane = new JScrollPane(contentPane);
            add(scrollPane);

            ActionPane actionPane = new ActionPane();
            actionPane.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridwidth = GridBagConstraints.REMAINDER;
                    gbc.weightx = 1;
                    gbc.fill = GridBagConstraints.HORIZONTAL;

                    EmployeeHistory history = new EmployeeHistory();
                    histories.add(history);
                    HistoryPane pane = new HistoryPane(history);
                    pane.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            pane.removeActionListener(this);
                            histories.remove(pane.getHistory());
                            contentPane.remove(pane);
                            contentPane.revalidate();
                            contentPane.repaint();
                        }
                    });
                    contentPane.add(pane, gbc, contentPane.getComponentCount() - 1);
                    contentPane.revalidate();
                    contentPane.repaint();
                }
            });
            add(actionPane, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

    }

    public class ActionPane extends JPanel {

        private JButton btn;

        public ActionPane() {
            setLayout(new GridBagLayout());
            btn = new JButton("Add");
            add(btn);
        }

        public void addActionListener(ActionListener listener) {
            btn.addActionListener(listener);
        }

        public void removeActionListener(ActionListener listener) {
            btn.removeActionListener(listener);
        }

    }

    public class EmployeeHistory {

        private String role;
        private String duration;
        private String employer;

        public EmployeeHistory() {
        }

        public EmployeeHistory(String role, String duration, String employer) {
            this.role = role;
            this.duration = duration;
            this.employer = employer;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getDuration() {
            return duration;
        }

        public void setDuration(String duration) {
            this.duration = duration;
        }

        public String getEmployer() {
            return employer;
        }

        public void setEmployer(String employer) {
            this.employer = employer;
        }

    }

    public class HistoryPane extends JPanel {

        private final JTextField txtRole;
        private final JTextField txtDuration;
        private final JTextField txtEmployer;

        private final JButton removeButton;

        private EmployeeHistory history;

        public HistoryPane(EmployeeHistory history) {
            // This is what you should use when you want to populate
            // the view or properties of the UI are changed
            this.history = history;
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;

            JLabel lblRoleHeld = new JLabel("Role Held:");
            add(lblRoleHeld, gbc);

            gbc.gridx++;
            txtRole = new JTextField();
            txtRole.setText("role");
            add(txtRole, gbc);
            txtRole.setColumns(10);

            gbc.gridx = 0;
            gbc.gridy++;
            JLabel lblDuration = new JLabel("Duration:");
            add(lblDuration, gbc);

            gbc.gridx++;
            txtDuration = new JTextField();
            txtDuration.setText("duration");
            add(txtDuration, gbc);
            txtDuration.setColumns(10);

            gbc.gridx = 0;
            gbc.gridy++;
            JLabel lblEmployer = new JLabel("Employer:");
            add(lblEmployer, gbc);

            gbc.gridx++;
            txtEmployer = new JTextField();
            txtEmployer.setText("employer");
            add(txtEmployer, gbc);
            txtEmployer.setColumns(10);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            removeButton = new JButton("Remove");
            add(removeButton, gbc);
        }

        public EmployeeHistory getHistory() {
            return history;
        }

        public void addActionListener(ActionListener listener) {
            removeButton.addActionListener(listener);
        }

        public void removeActionListener(ActionListener listener) {
            removeButton.removeActionListener(listener);
        }

    }

}

现在,说了这么多,去阅读如何使用表如何使用列表

Now, having said all that, go and have a read of How to Use Tables and How to Use Lists

数组会有所帮助吗?

Will an array be helpful?

不,不是这样.这将限制您可以显示的历史记录元素的数量.相反,我将使用ArrayList来管理历史对象的实例,如上所示

No, not really. This would limit the number of history elements you can display. Instead, I'd use a ArrayList to manage the instances of the history object, as demonstrated above

这篇关于如何使用"ADD"按钮反复添加JPanel?如何在ActionListener()中调用JPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆