再会,
我是 Java 编程的新手,目前正在学习这方面的课程。我们现在正在做一个项目,我们的任务是创建自己的类。到目前为止,我已经成功了。我的应用程序具有两种 JFrame 形式(JFrame1和JFrame2)。我使用的是 NetBeans 7.3.1 IDE,并且 JFrame1 设置为主类。
当我运行应用程序时,JFrame1 打开,我使用以下代码通过按钮设置类“公司”中的字段值:
public class JFrame1 extends javax.swing.JFrame
{
//Create company object and assign it to myCompany
company myCompany = new company(null, null, null, null, null);
private void btn_okActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
//Create variables to hold the user input from the form
String name = txt_company_name.getText();
String street = txt_address_street.getText();
String city = txt_address_city.getText();
String state = txt_address_state.getText();
String zip = txt_address_zipcode.getText();
//Assign the form data to the fields in the company class
myCompany.set_company_name(name);
myCompany.set_company_street(street);
myCompany.set_company_city(city);
myCompany.set_company_state(state);
myCompany.set_company_zipcode(zip);
//Display a friendly message informing user that input has been accepted
//then hide this form and display JFrame2.
JOptionPane.showMessageDialog(null, "Company data entered successfully, "
+ "application will now open.\nClick OK to proceed.", "THANK YOU!",
JOptionPane.INFORMATION_MESSAGE);
new JFrame2().setVisible(true); //Create new instance of my JFrame2 form and make it visible
this.setVisible(false); //Hide this form from view
}
}
在“公司”类中设置值后,表单关闭并打开我的JFrame2,其中有一个名为“ lbl_company_name ”的标签。我想用我以前使用 JFrame1 设置的“公司”类的字段值来设置这个标签的文本属性。
这是我迄今为止尝试过的,标签被更改为一系列空值。我有一种感觉,这是因为我使用“new”关键字来创建一个新对象——而不是拥有我需要的数据的那个对象。我对吗?
public class JFrame2 extends javax.swing.JFrame
{
//Create company object and assign it to myCompany
company myCompany = new company(null, null, null, null, null);
public void showCompanyInfo()
{
// Define variables and assign to them fields from my Company class
String name = myCompany.get_company_name();
String street = myCompany.get_company_street();
String city = myCompany.get_company_city();
String state = myCompany.get_company_state();
String zip = myCompany.get_company_zipcode();
// Use the variables above to manipulate the display of a label
lbl_company_name.setText(name + " | " + street + "," + city + "," + state + " " + zip);
}
/**
* Creates new form JFrame2
*/
public JFrame2()
{
initComponents();
jPanel1.setVisible(false);
showCompanyInfo();
}
}
非常感谢您的帮助,谢谢。