How to change jPanels in one frame with using ComboBox.getSelectedIndex()

Viewed 31

I want to switch panels with using ComboBox. For this, I defined a listener like:

cmbChooseAction.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            
            String whichPanel = cmbChooseAction.getSelectedItem().toString();
            
            getCurrentPanel(whichPanel);
            
        }
});

I am sending the String value this section as a parameter to the sql query: "from Database where name = ?" And I want to return WhichPanel value of the row that provides this query. So I wrote the following function:

public List<ComboBoxItem> getComboBoxItem(String where) {
    
    List<ComboBoxItem> cmbActions = new ArrayList<ComboBoxItem>();
    
    try {
        
        session.beginTransaction();
        
        cmbActions = session.createQuery("from ComboBoxItem where name = '" + where + "'").getResultList(); 
//name == action column
        
        session.getTransaction().commit();
        
    } finally {
        factory.close();
    }
    
    return cmbActions;
    
}

Database Image

public void getCurrentPanel(String where) {
    
    List<ComboBoxItem> resultList = comboBoxItemDal.getComboBoxItem(where);
    
    for(ComboBoxItem comboBoxItem: resultList) {
        switchPanel(comboBoxItem.getPanelName()); //It's invalid!
    }

}

-------------------------------------------------------------------------------------

My problem is I can't convert String to JPanel and looking for alternative solutions like this: (My English is a bit poor so I couldn't explain my problem completely)

public void switchPanel(JPanel panel) {
    
    //How should I change here?
    layeredPane.removeAll();
    layeredPane.add(panel);
    layeredPane.repaint();
    layeredPane.revalidate();
    
}

Can anybody help?

1 Answers

If you are curious, it can be solved CardLayout like @camickr said.

public void switchPanel(String panel) {

   CardLayout cardLayout = (CardLayout) (layeredPane.getLayout());
   cardLayout.show(layeredPane, panel)

}

However, when saving these panels, Eclipse IDE set them to layeredPane with a random name. Also need to pay attention here. The show method will recognize the String value here, you can change it as you like.

pnlSearch = new JPanel();
pnlSearch.setBackground(Color.WHITE);
layeredPane.add(pnlSearch, "name_89127391238sd");
// layeredPane.add(pnlSearch, "pnlSearch");
Related