在Java中使用getter/setter方法

5
我在访问其他类的变量方面遇到了一些问题。我曾经发布过一个帖子:Having access to a private variable from other classes in Java,在那里得到了一些有用的信息,我认为示例会更好地展示它并提出一个单独的问题。我有一个表单,可以向其中输入数据,它具有一个List变量。起初我没有将其设为静态变量,但我认为如果我需要从另一个类中获取总大小,那么我不会创建该类的实例以使用getTotalContacts函数。我基本上想通过我的状态栏更新列表中联系人的总数。其中一位成员在上述帖子中说要使用原始Foo成员来获取联系人,但我不确定这在这种情况下如何工作。欢迎任何想法。谢谢。
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);
                }
            }
        }
    }

}

我的另一个问题是,为什么我会得到错误提示“int cannot be dereferenced”?contactsLabel.setText(AddressbookForm.getTotalContacts().toString());。谢谢!
2个回答

2
请记住,通过将 addressList 变量声明为静态变量,它就属于 AddressbookForm 类而不是类的实例。这意味着所有的 AddressbookForm 实例都将共享相同的 addressList。我不确定这是否符合您的要求。
关于您的错误,AddressbookForm.getTotalContacts() 返回一个 int。由于在 Java 中,int 是原始数据类型,因此它没有 toString() 方法。可以使用以下方法将 int 转换为 String
int a = 5;
String aString = a + "";

1
Integer.valueOf(a).toString() - Rhangaun
你是对的,我不希望它是静态的。但即便如此,我仍然不确定如何访问这些变量... - Crystal
或者 String.valueOf(a)。/ 你真的不想使用静态可变对象。 - Tom Hawtin - tackline
这些方法为什么更好?我不确定Java在这里的底层操作是什么,即使Sun教程也列出了字符串拼接方法(http://java.sun.com/docs/books/tutorial/java/data/converting.html)。 - danben

0
在我看来,正确的解决方案是使用包装器 Integer 来代替原始类型 int。Integer 和 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() );
}

应该使用 Integer.valueOf(x) 而不是 new Integer(x)。 - unbeli
根据文档所述,如果您不需要新实例,则建议使用Integer.valueOf(x)。例如:如果您希望该方法的结果直接应用toString()方法。但是,如果您想要一个新实例来处理它,您应该使用构造函数。使用valueOf(x)会为经常使用的值使用缓存。从我的角度来看,如果您在面向对象编程范式下编程,应该忘记任何原始类型,这就是我想在示例中展示的内容。 - osanchezmon
为什么您想要一个新的 Integer 实例? - unbeli
@unbeli 为什么不想要一个新的 Integer 实例?这取决于你如何设计类,以便在代码的其他部分、其他计算等方面使用它。 - osanchezmon
1
你可以使用 Integer.valueOf() 返回的值,而不必严格获取新实例。更多的新实例 => 更多的垃圾。此外,Integer.valueOf() 更易读。 - unbeli
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接