问题描述
我想使用ComboBox切换面板。为此,我定义了一个监听器,例如:
cmbChooseAction.addPropertychangelistener(new Propertychangelistener() {
public void propertyChange(PropertyChangeEvent evt) {
String whichPanel = cmbChooseAction.getSelectedItem().toString();
getCurrentPanel(whichPanel);
}
});
我将此部分的String值作为参数发送给SQL查询:“来自数据库,其中name =?”我想返回提供此查询的行的WhothPanel值。所以我写了以下函数:
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;
}
public void getCurrentPanel(String where) {
List<ComboBoxItem> resultList = comboBoxItemDal.getComboBoxItem(where);
for(ComboBoxItem comboBoxItem: resultList) {
switchPanel(comboBoxItem.getPanelName()); //It's invalid!
}
}
-------------------------------------------- -----------------------------------------
我的问题是我无法将String转换为JPanel并寻找这样的替代解决方案:(我的英文有点差,所以我无法完全解释我的问题)
public void switchPanel(JPanel panel) {
//How should I change here?
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
有人可以帮忙吗?
解决方法
如果您感到好奇,可以像@camickr所说的那样解决CardLayout。
public void switchPanel(String panel) {
CardLayout cardLayout = (CardLayout) (layeredPane.getLayout());
cardLayout.show(layeredPane,panel)
}
但是,保存这些面板时,Eclipse IDE将它们设置为具有随机名称的layeredPane。这里也需要注意。 show方法将在此处识别String值,您可以根据需要更改它。
pnlSearch = new JPanel();
pnlSearch.setBackground(Color.WHITE);
layeredPane.add(pnlSearch,"name_89127391238sd");
// layeredPane.add(pnlSearch,"pnlSearch");