我无法访问Java中另一个类的变量值

我无法访问Java中另一个类的变量值,java,swing,Java,Swing,我有a类和B类。B类是从a类扩展而来的 在A班,我有这样一句话 JCombobox namecombo; JButton btnPrint = new JButton("Print"); btnPrint.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { CreateInvoiceTable op = new

我有a类和B类。B类是从a类扩展而来的

在A班,我有这样一句话

JCombobox namecombo; 

    JButton btnPrint = new JButton("Print");
    btnPrint.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            CreateInvoiceTable op = new CreateInvoiceTable();
            op.invoicetable();
            insertingBillNoIntoDatabase();
            String custname =namecombo.getSelectedItem().toString();
            MessageFormat footer = new MessageFormat(custname);
            MessageFormat header = new MessageFormat("SAHA TRADERS");
            try {
                table.print(JTable.PrintMode.FIT_WIDTH, header,footer);
            } catch (PrinterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            while(model_table.getRowCount()>0) {
                model_table.removeRow(0);
            }

            itemcombo.setSelectedIndex(0);



        }
    }); 
我从combobox中选择了名称,并点击按钮(打印)来执行类B

在B班

public void invoicetable() {

    String name = Invoice.namecombo.getSelectedItem().toString();

    System.out.println(name); 
}

public static void main(String[] args) {
    CreateInvoiceTable a = new CreateInvoiceTable();
    a.invoicetable();
}
}
现在当我打印它的时候。它只打印comboBox的第一个值,而不是

选中一个

这里的问题源于对实例变量访问的不了解

假设您已经在某处实例化了
ClassA
对象,并开始操作它。在某个时刻,
JCombobox
的值将会改变。这意味着它的状态仍然驻留在
ClassA
的实例中

在print方法中,创建一个新的
CreateInvoiceTable
实例,在该实例上调用
invoicetable
表。虽然您希望这将有效地为您提供访问驻留在
ClassA
对象中的
JCombobox
值的权限,但事实并非如此

实例化扩展类后,您将有效地创建它的新实例,这意味着一个新的
JCombobox
。这解释了为什么在第二个类的上下文中调用
getSelectedItem
时返回的值不正确

我假设此行
String custname=namecombo.getSelectedItem().toString()有效地返回正确的值,这将为您解决此问题提供线索

现在我最好的建议是停止从classB扩展classA。由于您的
invoicetable
方法将只打印一个名称和一张账单,因此只需将名称值作为参数传递给该方法即可

我还建议检查变量访问和继承,因为这些概念在您的头脑中似乎很混乱


希望这能有所帮助。

您需要提供更多的代码。@Aris_Kortex Okay现在我不知道要添加什么更多……我正在从数据库填充namecombo,希望你们能理解这个问题。@KaranMalhotra很好。如上所述,我们对继承和成员访问的工作原理有一个很好的了解。另外,请继续投票,并使这成为公认的答案。