卡布局和切换按钮问题

时间:2016-01-15 13:32:46

标签: java togglebutton cardlayout

使用卡片布局和切换按钮时出现问题。 我想在按下时更改背景按钮,例如:

private void togglebtnActionPerformed(java.awt.event.ActionEvent evt){
    if(togglebtn.isSelected()){
       togglebtn.setBackground(Color.green);}
    else{
       togglebtn.setBackground(Color.red);}
}

通过将此togglebtn放在普通的JFrame上,它可以工作。如果我使用带有CardLayout的Panel并使用CardLayout将此togglebtn放在此面板上,则它不起作用。

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);}
}

它只显示红色背景而不显示绿色背景,因此无法选择togglebutton。有一个CardLayout有什么区别?

1 个答案:

答案 0 :(得分:1)

我无法解释您在CardLayout处遇到的问题。事实上,我也无法用简单的JFrame来实现它 但是,如果要更改按钮的背景颜色,则需要使用以下命令对其进行初始化:

togglebtn.setContentAreaFilled(false);
togglebtn.setOpaque(true);

使其不透明,删除内容区域的填充确保您的ui外观&感觉不会画出你定义的背景颜色。