我有主jframe代码在类:
@SuppressWarnings("serial")
public class CreateBuildAndPr extends JFrame {
....some code...
private JComboBox comboBoxClients = new JComboBox();
private JComboBox comboBoxBranch = new JComboBox();
....some code...
public String getClient(){
String getClient = comboBoxClients.getSelectedItem().toString();
//System.out.printf("nClient: n" + getClient);
return getClient;
}
/**
* Create the frame.
*/
public CreateBuildAndPr() {
lblCreateBuildAnd.setFont(new Font("Tahoma", Font.BOLD, 11));
comboBoxBranch.setModel(new DefaultComboBoxModel(new String[] {"1a", "2a", "3a", "4a"}));
comboBoxClients.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3"}));
textFieldInfo.setColumns(10);
btnCreateBuild.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CreateNewBuildAndPr callSe = new CreateNewBuildAndPr();
callSe.newBuild();
}
});
initGUI();
}
所以当我调用这个方法getClient()时,在CreateBuildAndPr类中,从ComboBox选择的值是正确的。我们说:"2"。但是当我从其他类调用时,总是返回结果是"1"。下面是另一个类:
public class CreateNewBuildAndPr extends ConnectionsUrlAndDb {
@Test
public void newBuild() {
CreateBuildAndPr createBuildAndPr = new CreateBuildAndPr();
System.out.printf("nnSelenium: " +createBuildAndPr.getClient());
String info = createBuildAndPr.getInfo();
System.out.printf("nnSelenium: " +info);
String branch = createBuildAndPr.getBranch();
System.out.printf("nnSelenium: " +branch);
... more code .... }
我如何能纠正getSelectedItem在其他类?
这一行
CreateBuildAndPr createBuildAndPr = new CreateBuildAndPr();
创建该类的新对象。您需要的是使用JComboBox
及其所选值引用现有的一个。解决方案是将组合框(甚至是对包含它的帧的引用)作为参数传递给CreateNewBuildAndPr
对象。
例如修改你的CreateNewBuildAndPr
类来包含一个变量
private JComboBox clientCombo;
并在该类中定义一个新的构造函数
public CreateNewBuildAndPr (JComboBox clientCombo)
{
this.clientCombo = clientCombo
}
和在JFrame
ActionListener
传递组合框作为变量
CreateNewBuildAndPr callSe = new CreateNewBuildAndPr(comboBoxClients);
允许你在CreateNewBuildAndPr
类中引用这个组合框。
clientCombo.getSelectedItem()...
我在这里只使用单个JComboBox
作为示例。如果您传递了整个GUI对象,您可以访问它并使用它的方法,例如您似乎在那里的getInfo()
。