简体   繁体   English

JAVA JCheckBox需要2次单击进行检查,而1次单击则取消选中

[英]JAVA JCheckBox takes 2 clicks to check and 1 click to uncheck

The problem i have is that my JCheckBox need 2 clicks ( not double click ) to check and 1 click to uncheck. 我的问题是我的JCheckBox需要2次单击(而不是双击)进行检查,而1次单击则取消选中。 The rest of the code is perfectly working. 其余代码完全正常。

JCheckBox check = new JCheckBox(new ImageIcon("images/check.png"));
check.setOpaque(false);   

check.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent evt){
        for(int i = 0; i < tempPanel.length; i++)       
            if(check.getParent().equals(tempPanel[i])){
                if(!check.isSelected()){
                    JLabel tempLabel = new JLabel("Command "+(i+1));
                    tempLabel.setFont(new Font("Franchise",Font.BOLD,122));
                    tempLabel.setForeground(Color.BLACK);

                    tempPanel[i].setBorder(lineBorder);
                    tempPanel2[i].add(tempLabel);
                    secondScreenPanel.add(tempPanel2[i]);
                    secondScreenPanel.revalidate();
                    secondScreenPanel.repaint();
                    break;
                }

                if(check.isSelected()){
                     tempPanel[i].setBorder(null);
                     secondScreenPanel.remove(tempPanel2[i]);
                     tempPanel2[i].removeAll();
                     secondScreenPanel.revalidate();
                     secondScreenPanel.repaint();    
                }
            }
    }
});

Don't use a MouseListener. 不要使用MouseListener。

A JCheckBox is designed to be used with an ItemListener or ActionListener . JCheckBox设计为与ItemListenerActionListener Read the section from the Swing tutorial on How to Use Check Boxes for more information and examples 阅读Swing教程中有关如何使用复选框的部分, 获取更多信息和示例。

Try to create the JCheckBox withou listener, create a layout into you mainframe and check this code, It works fine for me: 尝试使用侦听器创建JCheckBox,在大型机中创建一个布局并检查此代码,它对我来说很好:

    jCheckBox1 = new javax.swing.JCheckBox();

    jCheckBox1.setText("jCheckBox1");
javax.swing.GroupLayout layout = new     javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(139, 139, 139)
            .addComponent(jCheckBox1)
            .addContainerGap(180, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(50, 50, 50)
            .addComponent(jCheckBox1)
            .addContainerGap(227, Short.MAX_VALUE))
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM