简体   繁体   English

在Java中使用getter / setter

[英]Using getters/setters in Java

I'm having some trouble with the idea of accessing variables from other classes. 我在从其他类访问变量的想法上遇到了一些麻烦。 I had a post here: Having access to a private variable from other classes in Java where I got some useful information, and thought an example would be better show it, and ask a separate question as well. 我在这里发了一篇文章: 从Java中的其他类访问一个私有变量 ,我获得了一些有用的信息,并且想一个例子可以更好地展示它,并且还要问一个单独的问题。 I have a form that I can input data to, and it has a List variable. 我有一个可以输入数据的表单,它有一个List变量。 I didn't make it static at first, but I thought if I needed to get the total size from another class, then I wouldn't create an instance of that class in order to use the function to getTotalContacts. 我一开始并没有让它变为静态,但我想如果我需要从另一个类中获取总大小,那么我就不会创建该类的实例来使用该函数来获取getTotalContacts。 I basically want to update my status bar with the total number of contacts that are in my list. 我基本上想用我列表中的联系人总数更新我的状态栏。 One of the members said in the above post to use the original Foo member to get the contacts, but I'm not sure how that works in this case. 其中一位成员在上面的帖子中说使用原来的Foo成员来获取联系人,但我不确定在这种情况下它是如何工作的。 Any thoughts would be appreciated. 任何想法将不胜感激。 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: " + AddressBookForm.getTotalContacts());
        add(this.statusBarString);
    }

    public void updateLabel()
    {
        contactsLabel.setText(AddressBookForm.getTotalContacts().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 static int getTotalContacts()
    {
        return addressList.size();
    }

    //void addContact(Person contact);

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

    private static 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);
                }
            }
        }
    }

}

My other question is why do I get the error, "int cannot be dereferenced contactsLabel.setText(AddressbookForm.getTotalContacts().toString()); Thanks! 我的另一个问题是为什么我得到错误,“int不能解除引用contactsLabel.setText(AddressbookForm.getTotalContacts()。toString());谢谢!

Keep in mind that by making addressList static, it belongs to the AddressbookForm class rather than to an instance of the class. 请记住,通过使addressList一成不变的,它属于AddressbookForm类而不是类的实例。 This means that all AddressbookForm s will be sharing the same addressList . 这意味着所有AddressbookForm旨意共享相同addressList I'm not sure if that is what you want. 我不确定这是不是你想要的。

Regarding your error, AddressbookForm.getTotalContacts() returns an int . 关于您的错误, AddressbookForm.getTotalContacts()返回一个int Since int is a primitive type in Java, it has no toString() method. 由于int是Java中的基本类型,因此它没有toString()方法。 An int can be converted to a String like: int可以转换为String如:

int a = 5;
String aString = a + "";

From my point of view the correct solution is to use the wrapper, Integer, for the primitive type int. 从我的观点来看,正确的解决方案是使用包装器Integer作为基本类型int。 Integer, like all the classes in Java, extends Object and in consequence has available toString() to override it or use it. 与Java中的所有类一样,整数扩展了Object,因此可以使用toString()来覆盖它或使用它。

// http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html
public static Integer getTotalContacts()
{
    return new Integer( addressList.size() );
}

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

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