[英]Call java swing controls and container from other class
我有一个关于如何从另一个类调用Java控件和容器的问题。 我有2个主意。
哪个最好? 还是还有另一个?
提前致谢
在考虑“提供吸气剂”与“公开财产”的选择时,“提供吸气剂”绝对是更好的选择。
但是,在这种特殊情况下,我认为我们可以做得更好。 也就是说,除了公开容器的内部细节之外,我们还可以在容器中提供有意义的操作(方法)。 我将通过以下示例尝试解释此概念。
在这里,我建议对getNameField
和getContactNumberField
getter进行setCustomer
操作。
(为了保持这个代码片断简单,我已经把一切都在一个班在这里。但在真实的情景frame
和customerPanel
将拥有自己单独的类。)
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.