2014-09-22 49 views
0

您好,我需要填寫ComboBox(ClassA)從ClassAddItem的幫助。從ComboBox中選擇「添加新條目」後,調用新窗口。當您單擊「添加新項目」(ClassAddItem)時,我想要將一個新項加入組合框ClassA。將項目從另一個JDialog添加到JComboBox

在ClassA中還有一個按鈕「Add New Item」它可以工作,但是如何從另一個類中向CB添加一個新項目?

項目「添加新項」的組合框是故意不數組的String [] cbItem的,因爲在我的應用可能性從文件加載,我不希望這個項目是文件中可見。另外,如果項目「添加新項目」仍然在組合框的末尾,這將是有利的。

感謝您迴應 對不起我的英文:)

public class ClassA extends JFrame { 
    private JPanel contentPane; 
    public JComboBox comboBox; 
    private String[] cbItem = {"A", "B", "C"}; 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        ClassA frame = new ClassA(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 
    public ClassA() { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 291, 152); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null);   
     comboBox = new JComboBox(cbItem); 
     comboBox.addItem("add new Item"); 
     comboBox.setBounds(10, 11, 116, 23); 
     comboBox.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       JComboBox comboBox = (JComboBox) event.getSource(); 
       Object selected = comboBox.getSelectedItem(); 
       if(selected.toString().equals("add new Item")) { 
        ClassAddItem cAI = new ClassAddItem(); 
        cAI.setVisible(true); 
       } 
      } 
     }); 
     contentPane.add(comboBox);   
     JButton btnAddNewItem = new JButton("add new item"); 
     btnAddNewItem.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       comboBox.addItem("this works"); 
      } 
     }); 
     btnAddNewItem.setBounds(136, 11, 116, 23); 
     contentPane.add(btnAddNewItem); 
    } 
} 

ClassAddItem:

public class ClassAddItem extends JDialog { 

    public ClassAddItem() { 
     setBounds(100, 100, 266, 155); 
     getContentPane().setLayout(null); 
     JButton btnNewButton = new JButton("Add new item"); 
     btnNewButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       ClassA cA = new ClassA(); 
       cA.comboBox.addItem("this does not work"); 
      } 
     }); 
     btnNewButton.setBounds(62, 11, 120, 23); 
     getContentPane().add(btnNewButton); 
    } 
} 

回答

0

您可以使用組合框使一個構造...

private JComboBox comboBox; 
//constructor 
public ClassAddItem(JComboBox box) { 
    this.comboBox = box; 
    .... 
} 

並在actionListener中使用此組合框

public void actionPerformed(ActionEvent e) { 
    this.comboBox.addItem("this does work"); 
} 
相關問題