简体   繁体   中英

Call java swing controls and container from other class

I have a question about how to call Java controls and containers from another class. I have 2 ideas.

  • Encapsulate containers in order to use GET method.
  • Switch property from Private to Public

Which is the best? Or is there another one?

Thanks in advance

When considering the options of "providing getters" vs "making properties public", "providing getters" is definitely the better option.

However, in this particular scenario, I think we can do even better. That is, instead of exposing internal details of container, we can provide meaningful operations (methods) in container. I'll try to explain this concept with below example.

Here I recommend setCustomer operation over getNameField and getContactNumberField getters.

(To keep this code snippet simple, I've put everything in one class here. But in a real scenario frame and customerPanel would have their own separate classes.)

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;

public class CustomerPanel extends JPanel
{
  private JTextField nameField = new JTextField(20);
  private JTextField contactNumberField = new JTextField(20);

  public CustomerPanel()
  {
    add(new JLabel("Name:"));
    add(nameField);
    add(new JLabel("Contact number:"));
    add(contactNumberField);
  }

  // Recommended approach
  public void setCustomer(String name, String contact)
  {
    nameField.setText(name);
    contactNumberField.setText(contact);
  }

  // Inferior approach. Hence commented out
  //public JTextField getNameField()
  //{
  //  return nameField;
  //}

  // Inferior approach. Hence commented out
  //public JTextField getContactNumberField()
  //{
  //  return contactNumberField;
  //}

  public static void main(String[] args)
  {
    // Recommended approach
    CustomerPanel customerPanel = new CustomerPanel();
    customerPanel.setCustomer("Kevin James", "72362282");

    // Inferior approach. Hence commented out
    //customerPanel.getNameField().setText("Kevin James");
    //customerPanel.getContactNumberField().setText("72362282");

    JFrame frame = new JFrame("Customers");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(customerPanel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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