与内部类相混淆,简单的动作 [英] Confused with Inner Classes, simple actions

查看:100
本文介绍了与内部类相混淆,简单的动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单设置,我一直在关注Core Java Vol I这本书如何设置表单,在那里他们有一个顶级类,该类扩展了JFrame创建不同组件的对象,并将它们布置在框架.如果这不是您通常"应该这样做的方式,请告诉我.

I have a simple form setup and I was following how the book, Core Java Vol I, sets up their forms, where they have a top level class that extends JFrame create objects of the different components, and lays them out in the frame. If this isn't the way you are "typically" supposed to do it, please let me know.

当我编写内部类以按下按钮时执行动作时,我感到困惑.我可以将内部类放在AddressBookForm类中,因为那是我放置按钮的地方,它可以访问JTextFields的私有变量.我遇到的问题(假设到目前为止其他部分都还可以),是我不知道如何获取addressList.size(),因此当插入按钮为时,我可以用总人数更新statusBar标签.按下.有什么想法吗?谢谢.

I got confused when I wrote my inner classes to perform actions when buttons were pressed. I could put my inner class in my AddressBookForm class since that's where I put my buttons and it would have access to the private variables of the JTextFields. The problem I have (assuming so far the other parts are 'ok'), is I don't know how to get the addressList.size() so I can update my statusBar label with the total number of people when the Insert button is pressed. Any thoughts? Thanks.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;

public class AddressBook
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                AddressBookFrame frame = new AddressBookFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JMenuBar menuBar = new JMenuBar();
                frame.setJMenuBar(menuBar);

                JMenu fileMenu = new JMenu("File");
                JMenuItem openItem = new JMenuItem("Open");
                JMenuItem saveItem = new JMenuItem("Save");
                JMenuItem saveAsItem = new JMenuItem("Save As");
                JMenuItem printItem = new JMenuItem("Print");
                JMenuItem exitItem = new JMenuItem("Exit");
                fileMenu.add(openItem);
                fileMenu.add(saveItem);
                fileMenu.add(saveAsItem);
                fileMenu.add(printItem);
                fileMenu.add(exitItem);
                menuBar.add(fileMenu);

                JMenu editMenu = new JMenu("Edit");
                JMenuItem newItem = new JMenuItem("New");
                JMenuItem editItem = new JMenuItem("Edit");
                JMenuItem deleteItem = new JMenuItem("Delete");
                JMenuItem findItem = new JMenuItem("Find");
                JMenuItem firstItem = new JMenuItem("First");
                JMenuItem previousItem = new JMenuItem("Previous");
                JMenuItem nextItem = new JMenuItem("Next");
                JMenuItem lastItem = new JMenuItem("Last");
                editMenu.add(newItem);
                editMenu.add(editItem);
                editMenu.add(deleteItem);
                editMenu.add(findItem);
                editMenu.add(firstItem);
                editMenu.add(previousItem);
                editMenu.add(nextItem);
                editMenu.add(lastItem);
                menuBar.add(editMenu);

                JMenu helpMenu = new JMenu("Help");
                JMenuItem documentationItem = new JMenuItem("Documentation");
                JMenuItem aboutItem = new JMenuItem("About");
                helpMenu.add(documentationItem);
                helpMenu.add(aboutItem);

                menuBar.add(helpMenu);

                frame.setVisible(true);

            }
        });
    }
}

class AddressBookFrame extends JFrame
{
    public AddressBookFrame() 
    {
        setLayout(new BorderLayout());
        setTitle("Address Book");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        AddressBookToolBar toolBar = new AddressBookToolBar();
        add(toolBar, BorderLayout.NORTH);
        AddressBookStatusBar aStatusBar = new AddressBookStatusBar();
        add(aStatusBar, BorderLayout.SOUTH);
        AddressBookForm form = new AddressBookForm();
        add(form, BorderLayout.CENTER);
    }
    public static final int DEFAULT_WIDTH = 500;
    public static final int DEFAULT_HEIGHT = 500;

}

/* Create toolbar buttons and add buttons to toolbar */
class AddressBookToolBar extends JPanel
{
    public AddressBookToolBar()
    {
        setLayout(new FlowLayout(FlowLayout.LEFT));
        JToolBar bar = new JToolBar();
        JButton newButton = new JButton("New");
        JButton editButton = new JButton("Edit");
        JButton deleteButton = new JButton("Delete");
        JButton findButton = new JButton("Find");
        JButton firstButton = new JButton("First");
        JButton previousButton = new JButton("Previous");
        JButton nextButton = new JButton("Next");
        JButton lastButton = new JButton("Last");
        bar.add(newButton);
        bar.add(editButton);
        bar.add(deleteButton);
        bar.add(findButton);
        bar.add(firstButton);
        bar.add(previousButton);
        bar.add(nextButton);
        bar.add(lastButton);
        add(bar);
    }
}

/* Creates the status bar string */
class AddressBookStatusBar extends JPanel
{
    public AddressBookStatusBar()
    {
        setLayout(new FlowLayout(FlowLayout.LEFT));
        this.statusBarString = new JLabel("Total: " + totalContacts);
        add(this.statusBarString);
    }

    public void updateLabel(int n)
    {
        contactsLabel.setText((new Integer(n)).toString());
    }

    private JLabel statusBarString;
    private JLabel contactsLabel;
}

class AddressBookForm extends JPanel
{
    public AddressBookForm()
    {   
        // create form panel
        this.setLayout(new GridLayout(2, 1));
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new GridLayout(4, 2));
        firstName = new JTextField(20);
        lastName = new JTextField(20);
        telephone = new JTextField(20);
        email = new JTextField(20);
        JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT);
        formPanel.add(firstNameLabel);
        formPanel.add(firstName);
        JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); 
        formPanel.add(lastNameLabel);
        formPanel.add(lastName);
        JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT);
        formPanel.add(telephoneLabel);
        formPanel.add(telephone);
        JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT);
        formPanel.add(emailLabel);
        formPanel.add(email);
        add(formPanel);

        // create button panel
        JPanel buttonPanel = new JPanel();
        JButton insertButton = new JButton("Insert");
        JButton displayButton = new JButton("Display");

        ActionListener insertAction = new AddressBookListener();
        ActionListener displayAction = new AddressBookListener();
        insertButton.addActionListener(insertAction);
        displayButton.addActionListener(displayAction);
        buttonPanel.add(insertButton);
        buttonPanel.add(displayButton);
        add(buttonPanel);
    }

    public int getTotalContacts()
    {
        return addressList.size();
    }

    private JTextField firstName;
    private JTextField lastName;
    private JTextField telephone;
    private JTextField email;
    private JLabel contacts;

    private List<Person> addressList = new ArrayList<Person>();

    private class AddressBookListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String buttonPressed = e.getActionCommand();
            System.out.println(buttonPressed);
            if (buttonPressed == "Insert") {
                Person aPerson = new Person(firstName.getText(), lastName.getText(), telephone.getText(), email.getText());
                addressList.add(aPerson);
            }
            else {
                for (Person p : addressList) {
                    System.out.println(p);
                }
            }
        }
    }

}

推荐答案

不要在组件中存储人员列表,这是紧密耦合的.

Don't store a list of persons in a component, that's tight coupling.

具有提供人员"列表的服务类或接口,诸如此类

Have a service class or interface that provides the list of Persons, something like this

public interface AddressBookService {

    List<Person> getContacts();

    void addContact(Person contact);

    void deleteContact(Person person);

}

现在通过注入或将其用作单例或任何其他查找方法,使每个组件都可以访问此服务.

Now give each of your components access to this service, either by injecting it or by using it as a singleton or any other lookup method.

这篇关于与内部类相混淆,简单的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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