2010-06-10 7 views
5

Mam problem z pomysłem uzyskiwania dostępu do zmiennych z innych klas. Miałem posta tutaj: Having access to a private variable from other classes in Java , gdzie dostałem kilka przydatnych informacji i pomyślałem, że przykład będzie lepiej pokazać to i zadać osobne pytanie również. Mam formularz, do którego mogę wprowadzić dane, i ma on zmienną List. Na początku nie uczyniłem tego statycznie, ale pomyślałem, że jeśli potrzebuję uzyskać całkowity rozmiar z innej klasy, to nie utworzę instancji tej klasy, aby użyć funkcji do uzyskaniaTotalContacts. Zasadniczo chcę zaktualizować pasek stanu o łączną liczbę kontaktów znajdujących się na mojej liście. Jeden z członków powiedział w powyższym poście, aby użyć oryginalnego członka Foo, aby uzyskać kontakty, ale nie jestem pewien, jak to działa w tym przypadku. Wszelkie przemyślenia będą mile widziane. Dzięki.Używanie modułów pobierających/ustawiających w języku Java

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

} 

Moje drugie pytanie jest dlaczego pojawia się błąd „int nie można dereferencjonowane contactsLabel.setText (AddressbookForm.getTotalContacts() toString().);! Dzięki

Odpowiedz

2

Należy pamiętać, że podejmowania addressList statyczne, należy do klasy AddressbookForm zamiast do instancji klasy. oznacza to, że wszystkie AddressbookForm s będą dzielić ten sam addressList. nie jestem pewien, czy to jest to, co chcesz.

dotycząceTwojego błąd, AddressbookForm.getTotalContacts() zwraca int. Ponieważ int jest typem pierwotnym w Javie, nie ma on metody toString(). Int może być przekształcany do String jak:

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

Integer.valueOf (a) .ToString() – Rhangaun

+4

'Integer.toString (a)' –

+0

Masz rację, nie ma to być statyczne. Ale nadal nie wiem, jak uzyskać dostęp do zmiennych ... – Crystal

0

Z mojego punktu widzenia poprawnym rozwiązaniem jest użycie opakowania, Integer do prymitywnego typu int. Integer, podobnie jak wszystkie klasy w Javie, rozszerza Object i w konsekwencji ma dostęp do toString(), aby go przesłonić lub użyć.

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

należy wykonać Integer.valueOf (x) zamiast nowego Integer (x) – unbeli

+0

@unbeli Ponieważ dokumentacja mówi, że Integer.valueOf (x) jest zalecany, jeśli nie potrzebujesz nowej instancji. Np. Jeśli chcesz, aby wynik tej metody był bezpośrednio stosowany do metody toString(). Ale jeśli chcesz, aby nowa instancja działała z nim, powinieneś użyć konstruktora. Przy użyciu valueOf (x) pamięć podręczna jest używana dla często używanych wartości. Z mojego punktu widzenia, jeśli programujesz w paradygmacie OOP, powinieneś zapomnieć o jakimkolwiek typie pierwotnym i właśnie to chcę pokazać w przykładzie. – ocell

+0

dlaczego chcesz nowej instancji Integer? – unbeli