【发布时间】:2016-04-21 02:48:03
【问题描述】:
我在使用卡片布局和切换按钮时遇到问题。 例如,我想在按下时更改背景按钮:
private void togglebtnActionPerformed(java.awt.event.ActionEvent evt){
if(togglebtn.isSelected()){
togglebtn.setBackground(Color.green);}
else{
togglebtn.setBackground(Color.red);}
}
把这个togglebtn 放在一个普通的JFrame 上就可以了。如果我使用带有 CardLayout 的面板并将此 togglebtn 放在带有 CardLayout 的面板上,它将不起作用。
private void cbItemStateChanged(java.awt.event.ItemEvent evt){ //cb is the combobox i use to switch the two panels
CardLayout cl = (CardLayout) (displaypane.getLayout()); //displaypane is the panel in which i used the CardLayout
if (cb.getSelectedIndex() == 0){
cl.show(displaypane, "card1"); //card1 is the first panel in displaypane
} else {
cl.show(displaypane, "card2"); //card2 is the second panel in displaypane
}
}
现在,如果我使用之前使用的相同代码,它就不起作用了:
private void togglebtnActionPerformed(java.awt.event.ActionEvent evt){ //the toggle button is in card1
if(togglebtn.isSelected()){
togglebtn.setBackground(Color.green);}
else{
togglebtn.setBackground(Color.red);}
}
它只显示红色背景而不显示绿色背景,因此无法选择切换按钮。 CardLayout 有什么区别?
【问题讨论】:
-
请提供 ssccee meta.stackexchange.com/questions/22754/…
标签: java togglebutton cardlayout