我有A类和B类。B类是从A类扩展而来的。
在班级AI中有此声明。
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);
}
});
我从组合框中选择了名称,然后单击按钮(打印)以执行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
。
在打印方法中,创建一个新实例,CreateInvoiceTable
在该实例上调用该invoicetable
表。虽然您希望这样做可以有效地使您能够访问JCombobox
驻留在ClassA
对象内的的值,但事实并非如此。
实例化扩展类后,您将有效地创建它的新实例,即new JCombobox
。这解释了为什么在getSelectedItem
第二类的上下文中调用时返回的值不正确。
我假设该行String custname =namecombo.getSelectedItem().toString();
有效地返回了正确的值,这将为您解决这个问题提供线索。
现在,我最好的建议是停止从classB扩展classA。由于您的invoicetable
方法只会打印出一个名字,因此您只需在其中传递名字值作为参数即可。
我还建议检查变量访问和继承,因为您似乎对这些概念感到困惑。
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句